使用JavaScript或Jquery动态删除html输入字段

时间:2018-02-28 11:22:01

标签: javascript jquery dom dom-manipulation

我有一个包含 1选择输入字段的表单。

当我在选择字段中选择其中一个选项时。我默认情况下创建一个包含文本输入字段的部分,一个关闭按钮和一个添加字段按钮,以添加更多输入文本字段。

一切正常,但我不确定如何删除动态创建的输入字段。我不确定当我点击旁边的删除按钮时,使用 id或类或名称属性或来查找和删除输入字段。

我的代码

HTML CODE

<div class="form-group">
    <div class="row">
        <div class="col-md-12" id="extraFieldsLabelHolder"></div>
    </div>
    <div class="row" id="extraFields">
      <!-- here I can add as many custom fields I want -->
    </div>
</div>

JS CODE

 function addFields(){
        var selectVal = document.getElementById('type_id').value;
        if(selectVal === 'checkbox' || selectVal === 'radio'){

            if(!document.getElementById("addBtn")){
                //add input fields
                var extraFieldDIV = document.getElementById("extraFieldsLabelHolder");
                var fieldLabel = document.createElement("label");
                    fieldLabel.setAttribute("for", "extraFields");
                    fieldLabel.setAttribute('id', "extraFieldsLabel")
                    fieldLabel.textContent = "Add Custom Field Options:";
                extraFieldDIV.appendChild(fieldLabel);

  //IT MAY LOOK COMPLEX BUT ITS FAIRLY STRAIGHTFORWARD
  //Code below creates mainDiv and a Div which holds input and a delete btn
                var fieldArea = document.getElementById('extraFields');
                var mainDiv = document.createElement("div");
                    mainDiv.setAttribute("class", "input_field col-md-4");
                    mainDiv.setAttribute("style", "margin-bottom:10px;");
                fieldArea.appendChild(mainDiv);

                var div = document.createElement("div");
                    div.setAttribute("class", "input-group");
                mainDiv.appendChild(div);

                var input = document.createElement("input");
                    input.setAttribute("type", "text");
                    input.setAttribute("class", "form-control input_field");
                    input.setAttribute("placeholder", "Enter value...");
                    input.setAttribute("name", "extras[]");
                div.appendChild(input);

                var span = document.createElement("span");
                    span.setAttribute("class", "input-group-btn");
                div.appendChild(span);

                var closeBtn = document.createElement("button");
                    closeBtn.setAttribute("type", "button");
                    closeBtn.setAttribute("class", "btn btn-danger");
       //YOU CAN SEE HERE I PASS ONCLICK METHOD but not sure what to do NEXT
       //ALL I GET IS INFO OF A DELETE BUTTON and Not the actual DIV which contains input field too.             
                closeBtn.setAttribute("onclick", "removeInputField(this)");
                span.appendChild(closeBtn);

                var iElement = document.createElement("i");
                    iElement.setAttribute("class", "pe-7s-close");
                    iElement.setAttribute("style", "font-size:20px");
                closeBtn.appendChild(iElement);

                var btnArea = document.getElementById('addFieldBtnHolder');
                var btn = document.createElement("button");
                    btn.setAttribute("type", "button");
                    btn.setAttribute("class", "btn btn-primary");
                    btn.setAttribute("style", "margin-top:15px;");
                    btn.setAttribute("onclick", "addInputField()");
                    btn.textContent = "Add Field";
                    btn.setAttribute('id', "addBtn");
                btnArea.appendChild(btn);
            }

        }else{
            if(document.getElementById("addBtn")) {
                document.getElementById("extraFieldsLabel").remove();
                document.getElementById("addBtn").remove();
                var inputs = document.getElementsByClassName('input_field');
                for(var i = 0; i < inputs.length; i++){
                    inputs[i].remove();
                }
            }
        }
    }

    function addInputField(){

        console.log("test2");
        var fieldArea = document.getElementById('extraFields');
        var mainDiv = document.createElement("div");
        mainDiv.setAttribute("class", "input_field col-md-4");
        mainDiv.setAttribute("style", "margin-bottom:10px;");
        fieldArea.appendChild(mainDiv);

        var div = document.createElement("div");
        div.setAttribute("class", "input-group");
        mainDiv.appendChild(div);

        var input = document.createElement("input");
        input.setAttribute("type", "text");
        input.setAttribute("class", "form-control input_field");
        input.setAttribute("placeholder", "Enter value...");
        input.setAttribute("name", "extras[]");
        div.appendChild(input);

        var span = document.createElement("span");
        span.setAttribute("class", "input-group-btn");
        div.appendChild(span);

        var closeBtn = document.createElement("button");
        closeBtn.setAttribute("type", "button");
        closeBtn.setAttribute("class", "btn btn-danger");
        closeBtn.setAttribute("onclick", "removeInputField(this)");
        span.appendChild(closeBtn);

        var iElement = document.createElement("i");
        iElement.setAttribute("class", "pe-7s-close");
        iElement.setAttribute("style", "font-size:20px");
        closeBtn.appendChild(iElement);
    }

//WHAT LOGIC DO I PUT HERE TO DELETE THE DIV CONTAINING input and delete button?
    function removeInputField (selectedField) {
        console.log("this: ", selectedField.value);

    }

2 个答案:

答案 0 :(得分:1)

您可以使用closest()

但它仅适用于现代浏览器。破解你可以阅读here

function removeInputField (selectedField) {
        selectedField.closest('.input_field').remove();
    }

参见示例

<style>
.input_field{border: 2px solid red;}
</style>

    <script>
	function removeInputField (selectedField) {
        selectedField.closest('.input_field').remove();
    }
	</script>
<div>
	<div class="input_field">i<button onclick="removeInputField(this);">1</button></div>
	<div class="input_field">am<button onclick="removeInputField(this);">2</button></div>
	<div class="input_field">another<button onclick="removeInputField(this);">3</button></div>
	<div class="input_field">element<button onclick="removeInputField(this);">4</button></div>
</div>

答案 1 :(得分:0)

如果你正在使用Bootstrap(你可能是因为OP类是BS),那么你可能正在使用jQuery(BS API需要jQuery)。所以这个Demo是在jQuery中。这就是它的作用:

  • 以3个按钮开始 +

    • ADD accountName lastDepoDate depositAmount currentBal prevBal User1 2018-01-25 16:09:05.000 20 20 20 User1 2018-01-06 17:43:58.000 20 20 1660 User1 2018-01-05 22:39:46.000 3160 3160 0 User1 2018-01-04 16:45:30.000 3000 3000 0 User2 2017-10-06 11:33:54.000 6000 6000 20 User2 2017-10-06 11:23:20.000 4000 20 420 User2 2017-09-24 10:48:49.000 500 500 0
    • CFG 设置(在演示中无效)
    • SUB 将表单数据转换为live test server
  • 每个fieldset.form-group都有:

    • 3 fieldset.form-group
    • 1 <input>
    • 2 <textarea>

      • CFG 设置(在演示中无效)
      • DEL ete <button>
    • 带有fieldset.form-group#id的每个元素都有一个唯一的后缀(基于[name]Date.now())。

    • SUB mitting Math.random()时,会显示一个链接。

      • 点击该链接可将用户滚动至form#frm0
      • `iframe #response接收并显示来自测试服务器的响应。

参考

Template Literals

演示

&#13;
&#13;
iframe#response
&#13;
// When button#ADD is clicked...  
$('#ADD').on('click', function(e) {

  /* Random number to be interpolated in 
  || Template Literal
  */
  var ts = Math.round(Date.now() / Math.random() * 11);

  /* Template Literal is a string with new 
  || syntax and advanced methods and properties
  */
  var str = `<fieldset id='setX${ts}' class='SET form-group'><div class="input-group"> <span class="input-group-addon"> <i class="glyphicon glyphicon-user"></i> </span> <input id="name-${ts}" type="text" class="form-control" name="name-${ts}" placeholder="Name"></div><div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i> </span><input id="mail-${ts}" type="email" class="form-control" name="mail-${ts}" placeholder="Email"><span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span><input id="cell-${ts}" type="phone" class="form-control" name="cell-${ts}" placeholder="Phone"></div><div class="input-group pull-right"><div id='setC${ts}' class="btn-group"><button id='CFG${ts}' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button> <button id="DEL${ts} "type="button" class="DEL btn btn-danger"> <i class='glyphicon glyphicon-minus'></i> </button></div></div> <span class="input-group-addon" style="height:35px">${ts}&nbsp;&nbsp;&nbsp;<i class="glyphicon glyphicon-info-sign"></i></span><textarea id="info-${ts}" type="text" class="form-control" name="info-${ts}" placeholder="Info" cols='120' rows='4'></textarea></fieldset>`;

  // Append TL to DOM (string gets parsed as HTML)
  $('#setD').append(str);

  // Register the new button.DEL to click event
  $('.DEL').on('click', DEL);
});

/* This the callback function for button.DEL
|| click event
*/
function DEL(e) {
  // Get the closest fieldset.SET and remove it
  var parent = $(this).closest('.SET').remove();
}

// When form#frm0 is submitted show a#RSP 
$('#frm0').on('submit', function() {
  $('#RSP').show();
});

/* When a#RSP is clicked, scroll to 
|| iframe#response.
|| iframe#response receives the server response
|| and displays it.
*/
$("#RSP").click(function() {
  $('html, body').animate({
    scrollTop: $("#response").offset().top
  }, 1000);
});
&#13;
#RSP {
  display: none
}
&#13;
&#13;
&#13;