3

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!

hindmost
  • 7,125
  • 3
  • 27
  • 39
Altair827
  • 329
  • 1
  • 2
  • 10

2 Answers2

1

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(){})
Ying Yi
  • 784
  • 4
  • 16
0

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.

Sayed
  • 601
  • 6
  • 21
  • 1
    The blur event didn't worked but the keyup event worked as it makes the first call when I type the first letter. I will use this. I changed the blur to keyup in my code. – Altair827 Sep 04 '16 at 09:10
  • Great! Also, make sure you handle events for keys like 'backspace', in which case, you already have the data! Also, if the answer helped you, please mark it as accepted answer! – Sayed Sep 04 '16 at 09:11
  • I will see to it. – Altair827 Sep 04 '16 at 09:13