0

I have a page where the user can dynamically add a text input box. I am wanting to fire an even when the user leaves this input box. This looks OK on the initial page refresh where there is only one box. In that case the DOM looks like...

<div id="controls">
<div class="tag" data-tag="1">
<input id="tags_" class="word" type="text" name="tags[]" data-tag="1">
<input id="weights_" class="weight" type="hidden" name="weights[]" data-tag="1" value="90">
<div class="slider slider-1 ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" aria-disabled="false">
<a class="add-word" href="1" data-tag="1">+</a>
</div>
</div>

...and my js is...

$('.word').blur(function(){
  alert("wintas!");
});

So this works OK, but if I add anohter text box dynamically the DOM becomes...

<div id="controls">
<div class="tag" data-tag="1">
<input id="tags_" class="word" type="text" name="tags[]" data-tag="1">
<input id="weights_" class="weight" type="hidden" name="weights[]" data-tag="1" value="90">
<div class="slider slider-1 ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" aria-disabled="false">
<a class="ui-slider-handle ui-state-default ui-corner-all" href="#" style="left: 80%;"></a>
</div>
<a class="remove-word" href="#" data-tag="1">-</a>
</div>
<div class="tag" data-tag="2">
<input class="word" type="text" name="tags[]">
<input class="weight" type="hidden" value="50" name="weights[]">
<div class="slider slider-2 ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" aria-disabled="false">
<a class="add-word" href="1" data-tag="2">+</a>
</div>
</div>

However, the blur event still fires on the first text box. How can I get my js event to 'update' when I add a new box?

Mark Locklear
  • 4,253
  • 1
  • 39
  • 67
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – dsgriffin Aug 22 '13 at 17:54

2 Answers2

1
$(document).on('blur', '.word', function(){
  alert("wintas!");
});
carter
  • 3,783
  • 4
  • 26
  • 39
0

Try this:

$('.word').on('blur',function(){
  alert("wintas!");
});
Farhan
  • 752
  • 4
  • 10