首页 > 解决方案 > 动态添加/删除输入行 javascript,jquery

问题描述

动态添加/删除输入行无法正常工作。这些行是使用 add 函数创建的,但没有正确删除。基本上删除函数调用不起作用。

$(document).ready(function(){
    var counter = 1; //initlal text box count
    $("#addButton").click(function () {
        if(counter > 3){
            alert("Only 3 textboxes allowed");
            return false;
        }
        var selectfield = $('#selectcolumnlist option:selected').val();
        var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
        newTextBoxDiv.after().html('<label>'+ selectfield + ' : </label>' + '<input type="text" name="textbox_' + selectfield + '" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" /><input type="button" value="Remove Button" class="remove_this" id="removeid" />');
        newTextBoxDiv.appendTo("#TextBoxesGroup");
        counter++;
        alert(counter);
    });

    $("#removeid").click(function() {
        alert("i'm in");
    });
}

标签: javascriptjquery

解决方案


假设您以正确的方式创建元素,我的意思是,使用唯一 ID,您应该使用event-delegation

// This example selects the element with the class 
// .removeid (here you need to set a specific class) or set something unique
// per new dynamically created element.
$("#TextBoxesGroup").on('click', '.remove_this', (function() {
    alert("i'm in");
}));

推荐阅读