JavaScript:如何从keyup事件中获取发件人输入元素的值? [英] JavaScript: How to get value of sender input element from keyup event?

查看:568
本文介绍了JavaScript:如何从keyup事件中获取发件人输入元素的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要捕获keyup事件以在用户键入输入时提供实时验证(仅当输入失去焦点时才会触发change事件).

I need to capture the keyup event to provide live validation when user is typing in an input (change event fires only when the input loses focus).

我无法获得触发evnt的输入的编辑值.

I am having trouble getting the edited value of the input that fired the evnt.

该代码还在计时器上运行,以防止用户键入时多次调用(仅每500毫秒触发一次).

The code also runs on timer to prevent multiple calls when user is typing (fires only every 500 ms).

我有几个带有"priceinput"类的输入,并分别附加到每个的keyup事件上,如下所示:

I have several inputs with class "priceinput" and attach to keyup event of each like the following:

<script language="javascript" type="text/javascript">
    var timer;
    $(document).ready(function() 
    {
        $(".priceinput").each(function() 
        {
            $(this).keyup(function(e) 
            { 
                clearTimeout(timer);
                timer = setTimeout(function() 
                {     
                //how to get the value of the input element that was changed?  
                var value = ???;
                    $.getJSON('/Validator/IsValidInput', { input: value },
                    function(response) 
                    {
                      //indicate if input is correct
                    });
                }, 500);
            });
        });
     });
</script>

为了获取发送者的输入值,我尝试了$(this).valthis.val()e.target.val(),但似乎都无法正常工作.

To get the sender input value, I have tried $(this).val, this.val(), e.target.val() but none seem to work.

如何获取发件人输入的值?

How do I get the value of the sender input?

推荐答案

问题是,在超时功能中,您丢失了对输入元素的"this"引用.尝试这样的事情:

The problem is that in your timeout function, you've lost the "this" reference to the input element. Try something like this:

$('.priceinput').keyup(function(e) {
  var $input = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() { 
    var value = $input.val();
    $.getJSON( ... );
  }, 500);
});

这篇关于JavaScript:如何从keyup事件中获取发件人输入元素的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆