I must be missing something .. not sure why my JavaScript is failing or not working
var discount = 10;
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2) + '%';
} else {
newTemp = discount;
}
} //end of outer if
Above script works when discount = "10.0%" But fails when discount = 10
maynot be best way, but all I am trying to do is if discount value contains % sign then setting newTemp variable with new value. Else just keep it as is.
Any idea, why control fails when discount value is = 10
I must be missing something .. not sure why my JavaScript is failing or not working
var discount = 10;
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2) + '%';
} else {
newTemp = discount;
}
} //end of outer if
Above script works when discount = "10.0%" But fails when discount = 10
maynot be best way, but all I am trying to do is if discount value contains % sign then setting newTemp variable with new value. Else just keep it as is.
Any idea, why control fails when discount value is = 10
Share edited Apr 15, 2014 at 1:56 Walter Stabosz 7,7555 gold badges47 silver badges78 bronze badges asked Apr 15, 2014 at 1:41 JagdishJagdish 2514 silver badges19 bronze badges 2- It fails how? What errors do you see? – p.s.w.g Commented Apr 15, 2014 at 1:46
- I do not see any error. I did quick debug by placing alert and it stops at if (discount.indexOf("%") > -1) if the value of discount=10 – Jagdish Commented Apr 15, 2014 at 2:06
2 Answers
Reset to default 4because "10%" is a string, therefore it has a indexOf
method, and 10 is probably an integer or number.
Try discount.toString().indexOf('%')
It's because you're not appending the '%' in the else branch.
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2);
} else {
newTemp = discount;
}
} //end of outer if
newTemp += '%';
also as Hugo said, the number 10 does not have the indexOf
method, which is a string method.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745097289a4611056.html
评论列表(0条)