Increment input value by 10 returns NaN

时间:2015-11-12 11:10:03

标签: jquery

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?

2 个答案:

答案 0 :(得分:2)

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="">

答案 1 :(得分:2)

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