简体   繁体   中英

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

ers. Can anyone explain to me why blur and focus events aren't working on appended input textfields?

As you can see in this JSFIDDLE . The input fields created in html seem to listen to the blur and focus event. But when you append an input textfield using the append button, suddenly the input textfields don't listen to the blur/focus events.

HTML

<input class="input" value="value 1">
<input class="input" value="value 2">
<div id="appendinput">Append a 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 you explain to me why this isn't working for the appended input textfields? Thank you in advance.

You need to delegate event to parent of dynamically added elements using on.

Live Demo

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

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, reference .

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