admin管理员组

文章数量:1327661

I have a hidden input #start thats value is used to display a range of returned data (it is the starting point of an index) each time you click #next I need to increase its value.

$("#next").click(function() {
  $("#start").val() + 80;
)};

is this correct? or is there a better way? thx all!

I have a hidden input #start thats value is used to display a range of returned data (it is the starting point of an index) each time you click #next I need to increase its value.

$("#next").click(function() {
  $("#start").val() + 80;
)};

is this correct? or is there a better way? thx all!

Share Improve this question edited Sep 17, 2010 at 20:28 KP. 13.7k3 gold badges42 silver badges60 bronze badges asked Sep 17, 2010 at 20:17 Dirty Bird DesignDirty Bird Design 5,55313 gold badges67 silver badges127 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 6

Try this (demo):

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

You need to convert the value to an integer, add whatever number to it, and save it back:

$("#next").click(function(){
      var startElement = $("#start");
      var value = parseInt(startElement.val(), 10);
      startElement.val(value + 80);    
});

Working sample: http://jsfiddle/QZgAf/

All you're doing is retrieving val and adding 80 to it, you're not actually setting it back to the value on the element. To do so try the following:

$("#next").click(function() {
  $("#start").val( parseInt($("#start).val()) + 80 );
)};

This is somewhat inefficient though, as you'll be selecting #start twice. Instead I'd cache the #start selection in a variable:

$("#next").click(function() {
  var startElement = $("#start");
  startElement.val( parseInt(startElement.val()) + 80 );
)};

Here's another way. It accesses the value attribute directly and uses ~~ to avoid the possible octal or NaN issues.

$("#next").click(function() {
     var start = document.getElementById("start");
     start.value = ~~start.value + 80;
});

Or better is to only run the selector for #start once if the button could be clicked more than once.

   // cache "start" outside the handler
var start = document.getElementById("start");

$("#next").click(function() {
     start.value = ~~start.value + 80;
});

Use a little closure pattern:

$("#next").click(function cli() {
    var v = 0;

    return function() {
        $("#start").html(v += 80);
    };
}());

本文标签: javascriptincrease a hidden input39s value based on click of buttonStack Overflow