jb.
jb.

Reputation: 23955

How do I get curent value of text element via jQuery

I have text input element and an event is fired on blur event and when user presses enter.

My problem is that if user inputs "foo" and presses enter val() function nevertheless returns null, after the blur event val() returns foo. As far as I understand it is due to the fact that value property of HTML input element is updated only when it looses focus. Could you please give me a work around.

Here is the exact code I use:

var meetmove_address_field_listener = function(e){
    var type = $(this).attr('data-marker-type');;
    var value = $(this).val();
    meetmove_map.geocodeAddress(type, value);
};

$(document).ready(function(){
    $('input[data-type="name"]').blur(meetmove_address_field_listener);
    $('input[data-type="name"]').keypress(function(event){
        if (event.which == 13){
            event.preventDefault();
            meetmove_address_field_listener(event);
            return false; 
        }
    });
});

Upvotes: 0

Views: 92

Answers (2)

jb.
jb.

Reputation: 23955

Well really Sudahir answer solved my issue --- i was misusing $(this) reference that changes meaning depending on context. Bu he deleted his answer so here is the working code:

$(document).ready(function(){
    $('input[data-type="name"]').blur(meetmove_address_field_listener);
    $('input[data-type="name"]').keyup(function(event){
        if (event.which == 13){
            event.preventDefault();
            var type = $(this).attr('data-marker-type');
            var value = $(this).val();
            meetmove_map.geocodeAddress(type, value);
            return false;
        }
    });
});

Upvotes: 1

Christian
Christian

Reputation: 19740

The value can be accessed straight away, you just need to use the correct handler. .keypress() will fire before the character is displayed in the input. Try .keyup() instead of .keypress() and it should work.

Upvotes: 3

Related Questions