1

我有一个textbox可以直接从键盘或鼠标单击输入值的地方。如果我用鼠标单击,则该值会从前一个值增加一。而从键盘我可以输入任何值。我的问题是如何检测任何用户输入的文本框的值。

假设如果通过键盘输入任何值,我需要重置为零。

这是我到目前为止得到的

function AddTrackingItem()
{
    var counter;


$("#Item_Count").keyup(function (event) {
    if(event.which == 13)
        counter = 0;   // if value is enter from keyboard then reset value
    else
    {
        counter = $("#Item_Count").val();
    }
});

TIA

4

2 回答 2

1

I am assuming the html looks something like this:

<input type="text" id="item_count" value="0" />
<input type="button" id="btn" value="Increment"/>

You'll need an event handler for clicks on the button (obviously), and an event handler for the change event on the input field. The click on the button will not trigger the change event, but changing the input field manually will. Therefore we can safely reset the counter to 0 if the user alters the field.

$('#btn').on( 'click', function() {
  $('#item_count').val( function( i, oldval ) {
    return (oldval*1) + 1;
  } );
} );

$('#item_count').on( 'change', function() {
  $('#item_count').val( '0' );
} );

Edit: There are only two ways of entering data. One is by keyboard. The other one is by the button. That means that if the change event isn't triggered by the button, 100% of the cases where the change event is triggered, it must be via the keyboard. You can alter the code a bit to include the .data(...) (docs) functionality of jQuery and do something like the following code. It will reset the input when it was altered, and subsequently the button was pressed.

$('#btn').on( 'click', function() {
  $('#item_count').val( function( i, oldval ) {
    if( $(this).data( 'fromKeyboard' ) == 1 ) {
      $(this).data('fromKeyboard', 0 );
      return 1;
    }
    return (oldval*1) + 1;
  } );
} );

$('#item_count').on( 'change', function() {
  $(this).data( 'fromKeyboard', 1 );
} );

Example on jsbin.

于 2013-10-22T17:41:07.460 回答
0

如果您不希望用户在文本框中手动输入值,为什么不将其设为只读?无论如何,如果你想做你坚持做的事。这是如何做到的。

$("#btn").click(function(){
    var currentVal = $("#item_count").val(); 
    var counter = parseInt(currentVal) + 1;
    $("#item_count").val(counter);
});

$("#item_count").keyup(function (event) {
    $("#item_count").val("0");
});

请注意,我没有输入键事件 (13) 的侦听器,因为我在 keyup 时将值更改为 0。如果您想在输入键上将值更改为 0,您可以执行代码中的操作。请记住将字符串转换为 int,以便您可以添加/增加值。当您执行 .val() 时,它会返回一个字符串而不是 int。希望这可以帮助。如果您有任何问题,请告诉我。

于 2013-10-22T18:44:34.813 回答