views:

70

answers:

2

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" id="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 :-(

A: 

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();
SLaks
I believe `focus` and `blur` do trigger those events as long as they're not part of an event handler. see http://api.jquery.com/focus/ . I have such a script working, actually.
carillonator
Uhm... I was hoping that would work but this is not the case. With that I am able to blur the field, or give focus to another, but nevertheless my_val is still undefined. :-(
Andrea
@carillonator: See http://docs.jquery.com/Events/focus, which explicitly says they don't. I checked the source to see if it changed in 1.4, but I don't see any code that would change it.
SLaks
@SLaks, I see what you're talking about (don't totally understand what it's saying), but I just tried this and it works as I said, putting the cursor in the input box and giving it focus:`$('#some_link').click(function() { $('#some_input').focus(); });`
carillonator
What version of jQuery?
SLaks
1.4, but I had something just like it working in 1.3.2 the other day.
carillonator
+1  A: 

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.

carillonator