Search code examples
jqueryinputfocusdynamically-generated

jQuery clear input, textarea text on focus from dynamically added inputs


I have jQuery script:

$("input:not(':input[type=button], :input[type=submit], :input[type=reset]'), textarea").each(function () {

var Input = $(this);
var default_value = Input.val();

$(Input).on("focus", function() {
    if(Input.val() == default_value) Input.val("");
}).on("blur", function() {
    if(Input.val().length == 0) Input.val(default_value);
});

});

Its working fine if inputs already on html, but how to make this work on dynamically added inputs?

First idea was to change:

$(Input).on("focus", function()

to

$(document).on("focus", Input, function()

but with no luck.

UPDATE

I think I found way to make it work properly on any inputs:

$(document).on("focus", "input:not(':input[type=button], :input[type=submit], :input[type=reset]'), textarea", function(e) {
if (e.target.value == e.target.defaultValue) {
    e.target.value = "";
}
}).on("blur", "input:not(':input[type=button], :input[type=submit], :input[type=reset]'), textarea", function(e) {
if (e.target.value == "") {
    e.target.value = e.target.defaultValue;
}
});

Solution

  • I think this is what you're after:

    $(".url_add").on("click", function (e) {
        $(this).prev(".elements").clone().insertBefore(this);
        e.preventDefault();
    });
    var default_value = $('input').val();
    $(document).on("focus", 'input', function () {
        if ($(this).val() == default_value) $(this).val("");
    }).on("blur", 'input', function () {
        if ($(this).val().length == 0) $(this).val(default_value);
    });
    

    jsFiddle example