0

I used this code to handle to event , but I want to fire one time if both of them or one of them occur.

$(document).on("keypress blur", ".pollOptionInput", function(e) {
  if (e.type == 'focusout' || e.keyCode == 13) {
    e.preventDefault();
    addPollOption();
    $('.btnAdd').focus();
  }
});

My code fire two time if I press enter key . how can I solve my problem ?

Rayon
  • 36,219
  • 4
  • 49
  • 76
Mike
  • 181
  • 2
  • 12
  • `e.type` will never be `focusout`..Try with `keypress` – Rayon Aug 18 '16 at 08:46
  • @Rayon but e.type is `focusout` in console – Mike Aug 18 '16 at 08:50
  • Try `$(document).on("keypress blur", ".pollOptionInput", function(e) { if (e.keyCode || e.which === 13) { e.preventDefault(); } else { addPollOption(); $('.btnAdd').focus(); } }); ` – Rayon Aug 18 '16 at 08:51

2 Answers2

1

It works without any problems. Maybe you attach event twice and that's the problem. Note that i changed a way of event attaching - read more

$(document).ready(function(){
  $(".pollOptionInput").on("keypress blur", function(e) {
    if (e.type == 'blur' || e.keyCode == 13) {
    e.preventDefault();
      //addPollOption();
      //$('.btnAdd').focus();
      console.log('EVENT!');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" class="pollOptionInput" />
<input type="text" class="pollOptionInput" />
<input type="text" class="pollOptionInput" />
Community
  • 1
  • 1
jacqbus
  • 457
  • 3
  • 13
0

Is this what you expect? You can pass the function on document this way:

    var myFunction = function() {
    addPollOption();
    $('.btnAdd').focus();
    //if you don't want an event occurs multiple times after one call:
    e.stopPropagation();
    }

    $('document')
    .keypress(myFunction)
    .blur(myFunction)
Simo
  • 431
  • 1
  • 7
  • 20