1

I'm trying to get both blur and keypress(13) to do the same thing on an element that has been appended. An obvious use for trigger(), right? Not working. I'm hoping I'm just being stupid and missing something obvious.

$(document).ready (function() {
  $("#btn").click (function() {
    $("#this-ul").append ("<li><input id='input1' type='text'></li><li><input type='text' id='input2'></li>");
    $("#input1").focus();
  });
  $("#this-ul").on ("blur", "#input1", function() {
    $("#input2").val ("blurred");
  });
  $("#this-ul").on ("keypress", "#input1", function (e) {
    if (e.which == 13) {
      // Want to trigger $("#this-ul").on ("blur"...) as above
    }
  });
});
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

<button id="btn" type="button">Click</button>
<ul id="this-ul"></ul>
Nhan
  • 3,595
  • 6
  • 30
  • 38
DonSea
  • 23
  • 4

1 Answers1

0

Try this :

$(document).ready (function() {
    $("#btn").click (function() {
        $("#this-ul").append ("<li><input id='input1' type='text'></li><li><input type='text' id='input2'></li>");
        $("#input1").focus();
    });
    $("#this-ul").on ("blur", "#input1", function() {
        $("#input2").val ("blurred");
    });
    $("#this-ul").on ("keypress", "#input1", function (e) {
        if (e.which == 13) {
            $(this).trigger("blur");
        }
    });
});

Fiddle here : https://jsfiddle.net/2b10cyez/

On blur of input 1, input 2 gets the value "blurred".
And on [enter] keypress, the blur event is triggered.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64