简体   繁体   English

如何通过 jQuery 获取文本元素的当前值

[英]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.我的问题是,如果用户输入“foo”并按下 enter val() function,在模糊事件val()返回 foo 之后仍然返回 null。 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.据我了解,这是由于 HTML 输入元素的值属性仅在失去焦点时才会更新。 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. .keypress()将在字符显示在输入中之前触发。 Try .keyup() instead of .keypress() and it should work.尝试.keyup()而不是.keypress() ,它应该可以工作。

Well really Sudahir answer solved my issue --- i was misusing $(this) reference that changes meaning depending on context.好吧,Sudahir 的回答真的解决了我的问题 --- 我误用了 $(this) 引用,它根据上下文改变了含义。 Bu he deleted his answer so here is the working code: Bu 他删除了他的答案,所以这里是工作代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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