开发者

Get input value after keydown/keypress

I have an <input type="text">, and I need to call a function after the text in the text box wa开发者_JAVA技巧s changed (inluding actions performed during jQuery's keydown and keypress handlers).

If I call my function from the jQuery handler, I see the value (e.target.value) as it was before the input was added. As I don't want to manually add the input onto the value every time, how I can call my function and have it use the updated value?


If I understand you right then something like this is the way u can do it

$('input').bind('change keydown keyup',function (){
   /// do your thing here.
   //  use $(this).val() instead e.target.value
});

Updated: 03/05/13

Please note: that you are better off to use .on() as oppose to .bind()

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

For more information jQuery Bind


You can use keyup - so you are only calling it once the key has been released:

$("#idofinputfield").keyup(function() {
    youFunction($(this).val());
});


You can generate the future value by taking the position where the new character will be inserted:

$('input').bind('keypress',function (){
   var value = e.target.value,
        idx = e.target.selectionStart,
        key = e.key;
        value =  value.slice(0, idx) + key + value.slice(idx + Math.abs(0));
    return yourfunction(value);
});


Have u tried out

$('#target').keyup(function(){       
     alert($(this).val());      
});


if you need to bind to an element up in the hierarchy, you can subscribe to the keyUp event in the keyDown handler.

$("#container").keydown(function (e) {
   //here you decide whether to handle the key event, and grab the control that sent the event 
   var myInput = e.target;
   $("#container").one('keyup', function() {
      console.log(myInput.val());  
      // do smth here
   });
});


You should use event.key to get the current input value before it is displayed in textbox.

Here is the code.

function validate()
{
  document.getElementById("divOutput").innerHTML = event.key;
  //I am here returning false so that you can see that this value is being entered before the text is input. This is very useful for number validation purposes.
  return false;
}
Enter Number: <input type="text" id="txtInput" onkeydown="return validate()" /><br />
You Entered <div id="divOutput"></div>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜