开发者

jQuery: val() updated too late

开发者 https://www.devze.com 2022-12-17 02:03 出处:网络
UPDATE: there was a problem with some other code. I\'m trying to get the value of some input text field. The problem is that the value I obtain by

UPDATE: there was a problem with some other code.

I'm trying to get the value of some input text field. The problem is that the value I obtain by

my_val = $('#MyInput').val();

is not really updated.

If I write in the field 'foo' and then click on the element which triggers the script, then I get my_val = undefined.

On the other hand, if I write in the field 'foo', CLICK SOMEWHERE ELSE, and then click on the element which triggers the script, then I get my_val = 'foo'.

It looks like Firefox updates val only on blur. Is there a way to get the correct value? (No, $('#MyInput').blur() does not work).

EDIT: I add more info as requested. I'm currently using Firefox 3.5 on Ubuntu 9.10, but the same happens on the latest beta of Chrome.

The simplest example is

<p>Bar</p>
<form>
<input type="text" i开发者_如何转开发d="input" />
</form>

and then a Javascript of

$('p').click(function() {
    my_val = $('#input').val();
    alert(my_val);
});

Try writing something in the input and then clicking on the paragraph without leaving the field.

EDIT2: never mind, it was some other code that was interfering. Sorry for wasting your time :-(


Just use the .keyup() event handler on your input to change your variable each time the contents change:

var my_val;

$('#MyInput').keyup(function() {
    my_val = $(this).val();
});

$('p').click(function() {
    alert(my_val);
});

Note that .change() won't work since it too only fires on blur.


Calling jQuery's blur and focus methods will call all event handlers that registered for the event, but won't actually change the focus.

You need to manually focus a different element, like this:

document.getElementById('something').focus();

If you do this using jQuery, you'll need to write [0] so that you call the DOM focus method, not the jQuery focus method.
For example:

$('input')[0].focus();
0

精彩评论

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