H.HISTORY
H.HISTORY

Reputation: 518

Increment input value by 10 returns NaN

I'm trying to increment an input value by 10 every time I click on a button but all i get is NaN in my input field. This is what I have done so far:

<button id="add">Add +10</button>
<input type="text" class="loadmoretxt" value="">
$("#add").click( function() {    
    var loadmorevalue = parseInt($(".loadmoretxt").val(), 10) + 10;
    $(".loadmoretxt").val(loadmorevalue);
    var amounttoload = $(".loadmoretxt").val();     
});

http://jsfiddle.net/WXAvS/153/

What I am doing wrong?

Upvotes: 1

Views: 323

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337550

The issue is on initial load the input has no value set. This means parseInt() returns NaN. You can use || to provide a default value of 0 in this instance:

var loadmorevalue = parseInt($(".loadmoretxt").val() || 0, 10) + 10;

Also note that you can simplify your logic by providing a function to the val() method:

$("#add").click(function () {
    $(".loadmoretxt").val(function(i, v) {
        return parseInt(v || 0, 10) + 10;
    }) 
});

Example fiddle

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Because when the value is empty parseInt('', 10) returns NaN

$("#add").click(function() {
  $(".loadmoretxt").val(function(i, val) {
    return (parseInt(val, 10) || 0) + 10;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add +10</button>
<input type="text" class="loadmoretxt" value="">

Upvotes: 2

Related Questions