Adding jQuery placeholders to dynamically created form elements

▼魔方 西西 提交于 2019-12-13 04:01:43

问题


Has anyone successfully added jQuery placeholder text for IE8 to dynamically created form elements.

For example, I click a button and a form appears that is loaded through AJAX, I need to hit the new form with placeholder text.

I have tried using jQuery .live, .bind, .on etc... but neither are catching the new elements when they are created.

I've also tried placing it in a click function so that when they click the button the placeholder function is activated.

$('input[placeholder]').on("focus", function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur().parents('form').submit(function() {
    $(this).find('input[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    })
});

回答1:


$(document).on({
    focus: function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    },
    blur: function() {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }
},"input[placeholder]");


$(document).on("submit","form",function() {
    $(this).find('input[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    });
});

$('input[placeholder]').blur();

Let me know if this refactoring works.



来源:https://stackoverflow.com/questions/13163872/adding-jquery-placeholders-to-dynamically-created-form-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!