1

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

2
  • It fails how? What errors do you see? 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 Commented Apr 15, 2014 at 2:06

2 Answers 2

4

because "10%" is a string, therefore it has a indexOf method, and 10 is probably an integer or number.

Try discount.toString().indexOf('%')

Sign up to request clarification or add additional context in comments.

3 Comments

I think you are right, it is treating 10 as number, however i tried your .toString() solution but did not work
it is too hard to help you with the information you provide. You should consider improving your debugging process - getfirebug.com/javascript
thank you for your feedback, i changed a logic little bit but understood overall issue was because of variable value is treated as number.
0

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.

1 Comment

.toString() was the key for me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.