[removed] How to get value of sender input element

2019-04-30 01:51发布

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).

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

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

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>

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-30 02:35

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);
});
查看更多
手持菜刀,她持情操
3楼-- · 2019-04-30 02:53

In Internet Explorer it should be event.srcElement, in Firefox event.target.
Or try event.toElement and event.relatedTarget.

(and of course combine them with .value or .val())

查看更多
登录 后发表回答