techie_28
techie_28

Reputation: 2133

keypress handler canceling the event

I have the following code

 jQuery('#parent').on('keypress', '.textbox', function(e) {
    var btn = jQuery(this).closest('tr').find('.btn');
    if (btn.length) {
        btn.triggerHandler('click');
    }
});

This code is a delegated keypress handler which is listening to the event of textboxes having class value ".textbox". The handler finds the button with class ".btn" & calls its click handler which has an ajax call in it.

Problem is this seems to prevent the event from completing i.e if the value in box is "2" & I type in a "3",the handler executes but the value in the box remains to be "2" instead of a "23".

It works normal when I comment out the btn triggerHandler statement.

Ideas why this is happening?

Upvotes: 2

Views: 194

Answers (3)

Vatsal Pathak
Vatsal Pathak

Reputation: 68

Try to use 'onchange' insted of 'keypress' or 'keyup'

  $(document).ready(function(){
  $("input").onchange(function(){
  var rs= $(this).val();
  alert(rs);
  $("input").css("background-color", "pink");
  });
});

Upvotes: 0

Developer107
Developer107

Reputation: 1758

Use keyup instead of keypress. As in your script you have triggered another event.

jQuery('#parent').on('keyup', '.textbox', function(e) {
   var btn = jQuery(this).closest('tr').find('.btn');
   if (btn.length) {
     btn.triggerHandler('click');
   }
});

keypress gets interrupted by triggerHandler and hence doesn't allow the default action of key press to occur. While keyup will perform default action first, then listen to handler.

Upvotes: 1

Akram Khan
Akram Khan

Reputation: 114

I think you need to keyup function.

$(document).ready(function(){
   $("input").keyup(function(){
var rs= $(this).val();
  alert(rs);
        $("input").css("background-color", "pink");
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Enter your value: <input type="text">

Upvotes: 0

Related Questions