Reputation: 241
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
Upvotes: 1
Views: 7695
Reputation: 7735
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.
Upvotes: 0
Reputation: 6948
because "10%" is a string, therefore it has a indexOf
method, and 10 is probably an integer or number.
Try discount.toString().indexOf('%')
Upvotes: 4