Skip to content Skip to sidebar Skip to footer

Simple Math In Jquery

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50.

Solution 1:

Parentheses should be used.

 ($('#selectform').val()*1 + 1) *50;

Your current expression is interpreted as:

var something = $('#selectform').val();
 var another   = 1 * 50;
 var result    = something + another

The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:

var something = $('#selectform').val() + "1";  //String operationvar result    = something * 50;    // something is converted to a number, and//    multiplied by 50

Solution 2:

Correct parentheses and use parseInt function -

(parseInt($('#selectform').val(),10) +1) *50;

Solution 3:

The data from $('#selectform').val() is probably being treated as a string. Use parseInt($('#selectform').val()) to convert it to an int before the multiply.

Solution 4:

You should have a look at the operator precedence in JavaScript.

Solution 5:

You need to force the addition to happen before the multiplication with parentheses:

barmyVal= ($("#selectform").val() + 1) * 50;

Post a Comment for "Simple Math In Jquery"