简体   繁体   中英

Javascript Increase value of textbox +1

Basically I'm looking for something in JavaScript for a live webpage that can increase the current numeric value of a text box by 1 each time as a user is typing.

For example

<td> <input type='text' name='form_c_port' value='1' size='5' maxlength='5'/> </td>

And then my next text box value should be 2 increases by 1 or decreases by 1 everytime the numeric value of the other textbox changes

<td> <input type='text' name='form_q_port' value='0' size='5' maxlength='5'/> </td>

But I cant seem to find out how to increase the value by one in JavaScript. I know how to do this in PHP, but I need to it to be done on the live webpage as a user changes the value.

This was a lot more complicated than I originally thought. I didn't realize that both inputs could be modified. I finally got it working by listening for the backspace and delete on the first input. It still has bugs if the input is too fast it seems.

Here is the HTML

<td> <input id="one" type='text' name='form_c_port' value='1' size='5' maxlength='5'/> </td>
<td> <input id="two" type='text' name='form_q_port' value='0' size='5' maxlength='5'/> </td>

Here is the jQuery

var lengthValue = $('#one').val().length;
$('#one').keyup(function(event){
    var key = event.keyCode || event.charCode;
    var tempLength = $('#one').val().length;
    if(key == 8 || key == 46){
        if(tempLength < lengthValue){
            lengthValue = $('#one').val().length;
            if(isNumber($('#two').val())){
              $('#two').val(parseFloat($('#two').val()) - 1);   
            }
            else{
              $('#two').val(0);    
            }
        }
    }
    else if(lengthValue < 5){
       lengthValue = $('#one').val().length;
       if(isNumber($('#two').val())){
          $('#two').val(parseFloat($('#two').val()) + 1);   
       }
       else{
          $('#two').val(0);    
       }
    }
});


function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

And here is a link to a fiddle .

向您的输入元素添加onkeydown侦听器,该侦听器将检查文本的当前大小并更新值。

Add an onkeydown() event to the objects, so:

<input type='text' name='form_q_port' value='0' size='5' maxlength='5' onkeydown="increaseValue(this)"/>

Then JS:

function increaseValue(object)
{
object.Value += 1;
}
document.getElementsByName("form_c_port")[0].value = parseInt(document.getElementsByName("form_c_port")[0].value) + 1

参见http://jsfiddle.net/NK6dB/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM