jquery - Why is on blur and focus not working on appended input textfield? -


ers. can explain me why blur , focus events aren't working on appended input textfields?

as can see in jsfiddle. input fields created in html seem listen blur , focus event. when append input textfield using append button, input textfields don't listen blur/focus events.

html

<input class="input" value="value 1"> <input class="input" value="value 2"> <div id="appendinput">append input textfield</div> <div id="inputcontainer"></div> 

jquery

var counter = 0;  $("#appendinput").click(function () {     $('<input class="input" value="value 3" type="text" id="input' + (counter) + '"/>').appendto('#inputcontainer');     counter++; });   $('.input').on('focus', function () {     thisvalue = $(this).val();     $(this).attr("value", ""); }); $('.input').on('blur', function () {     if ($(this).val() === "") {         $(this).val(thisvalue);     } }); 

can explain me why isn't working appended input textfields? thank in advance.

you need delegate event parent of dynamically added elements using on.

live demo

$(document).on('focus', '.input', function () {     thisvalue = $(this).val();     $(this).attr("value", ""); }); 

delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers, reference.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -