简体   繁体   中英

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; 
        }
    });
});

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.

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;
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM