3

I opened a jquery modal dialog which has 2 textboxes and a button

<table cellpadding="0" cellspacing="0">
        <tr>
          <td align="center"><input name="" type="text" value="" title="User Name" class="width190 enter_popup" id="txtUserName" onfocus="txtFocus(this)" onblur="txtFBlur(this,'0')"/></td>
          <td align="center"><input name="" type="password" value=""  title="Password" class="width190 enter_popup" id="txtPassword" onfocus="txtFocus(this)" onblur="txtFBlur(this,'1')"/></td>
        </tr>
        <tr>
          <td colspan="2" align="center"><input name="" type="submit" class="blue_btn" value="Sign In"  id="btnLogIn" onclick="javascript:return LogIn()"/></td>
        </tr>

      </table>

now in my script I'm calling LogIn function

$(function () {

    $(".enter_popup").keypress(function (e) {
        if (e.keyCode == 13) {
            if ($(this).attr('id') == "txtUserName" || $(this).attr('id') == "txtPassword") {
                LogIn();
            }

        }
    });
 });

function LogIn() {
    var username = $('#txtUserName').val();
    var password = $('#txtPassword').val();
}

but keypress is not fired..any ideas why and what is possible solution for that?

Sid M
  • 4,354
  • 4
  • 30
  • 50
  • 1
    Works fine here http://jsfiddle.net/dzxu1c8s/ so i'm guessing that the element is dynamically created thus needing `event-delegation` `$(document).on('keypress','.enter_popup',function(){/*code*/});` – Anton Oct 13 '14 at 14:50
  • also verified that your code is working. try Anton's solution above. – mikelt21 Oct 13 '14 at 14:57
  • 1
    @Anton: this `$(document).on('keypress','.enter_popup',function(){/*code*/});` worked for me.. post it as answer. – Sid M Oct 14 '14 at 06:55
  • Possible duplicate of [detect key press on modal dialog not working](https://stackoverflow.com/questions/34351044/detect-key-press-on-modal-dialog-not-working) – Vic Seedoubleyew Jul 18 '19 at 14:22

3 Answers3

4

You need to use event-delegation on dynamically created elements

$(document).on('keypress','.enter_popup',function(){
    /*Your code*/
});
Anton
  • 32,245
  • 5
  • 44
  • 54
0

try to use the Keydown or Keyup events instead:

$(function () {

$(".enter_popup").keyup(function (e) {
    if (e.keyCode == 13) {
        if ($(this).attr('id') == "txtUserName" || $(this).attr('id') == "txtPassword") {
            LogIn();
        }

    }
});
Pascal
  • 122
  • 5
0

I find it a better solution to give focus to the modal, it worked for me.

In order to do that, you have to add a tabindex parameter to your modal container, and then set its focus using JavaScript. Once that's done it can receive keyboard events: https://stackoverflow.com/a/6633271/2873507

Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76