Mehedee Rahman Setu
Mehedee Rahman Setu

Reputation: 107

Plus operator problems in Jquery

I was trying with following script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#item1_number_1').keyup(function() {
            var valone = $('#item1_number_1').val();
            var valtwo = 5;
            var total = ((valone) + (valtwo));
            $('#item2_number_1').val(total.toFixed(2));
        });
    });
</script>

I do not get any result in the field. But when I assign multiple (*) instead of plus (+), I am getting result.

I cannot understand what the error is in "var total = ((valone) + (valtwo));"

Upvotes: 1

Views: 6669

Answers (5)

Suman Bogati
Suman Bogati

Reputation: 6349

Use parseInt() to convert fetched value(valone ) to number, and calculate, something like this, please use this only when your number is not float(56.66),

var valone =  parseInt($('#item1_number_1').val(), 10);
var valtwo = 5;
var total = ((valone) + (valtwo));

The fetched vaue is treated like string until you convert it into number.

UPDATE

After Archer pointed out, I came to know you are using toFixed() method, which supposed to expect float numbers. So in this case you should use parseFloat() as given below.

 var valone = parseFloat($('#item1_number_1').val());

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

The value of an input is always a string. "Adding" a string concatenates, giving another string. Strings do not have a toFixed method.

* however is unambiguously "multiply", giving a number and therefore a result.

var valone = parseFloat(document.getElementById('item1_number_1').value);

Upvotes: 2

Quentin
Quentin

Reputation: 943214

You can only call toFixed on Numbers.

String * String will convert the strings to Numbers and multiply them giving you a Number.

String + String will concatenate the two Strings together giving you a String.

You need to convert the strings to Numbers manually before you try to add them together.

var total = (+valone) + (+valtwo);

Then Number + Number will add the two Numbers together giving you a Number.

Upvotes: 4

Eli Gassert
Eli Gassert

Reputation: 9763

The issue is the + operator can also be used to concat strings together. The * operator is ONLY for multiplication and therefore it implicitly converts your values to numbers.

So you either need to use parseInt, parseFloat, or Number to explicitly convert to a numeric type before using the + operator.

Upvotes: 0

Mike Bovenlander
Mike Bovenlander

Reputation: 5426

I think one of them is a string. Try parseInt(valone) to make it an int first.

Upvotes: 0

Related Questions