简体   繁体   中英

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!

You can try this code:

var lazyTriggerEvent = function(id,event,callback){
    var searchTrigger=null;
    $("#"+id).bind(event,function(){
        var text = $.trim($(this).val());
        clearTimeout(searchTrigger);
        searchTrigger = setTimeout(function(){
            callback(text);
        },500);
      })
   };
//use keyup event
lazyTriggerEvent("event-name","keyup",function(){})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM