javascriptphpjqueryhtml.post

blur event doesn't trigger at first attempt


I'm trying to update the DOM based on the value entered in a text box.

HTML:

<input id="event-name" type="text"/>

JQUERY:

$('#event-name').on('blur',function(){
  $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
  //my code here
  });
});

this works on the first blur in Chrome. When I tried it in opera, mozilla and edge it doesn't worked on the first attempt.

It worked when I added this before the jquery.

$("#event-name").focus();
$("#event-name").blur();
$("#event-name").focus();

I did this to make the first $.post call to occur when the page opens.

Why is this problem happening? How to solve this in a proper way? Please help!


Solution

  • It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. The following solution should help you:

    $(document).on('blur','#event-name', function(){
      $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
      //my code here
      });
    });
    

    Alternatively, you could use keyup event. You can do so following:

    $(document).on('keyup','#event-name', function(){
      var eventName = $(this).val();
      $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
      //my code here
      });
    });
    

    Also, using - in IDs is not a good approach. Rather, either stick to camelCase or underscore_format of naming convention.