Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

dynamically delete html input field using JavaScript or Jquery

I have a form which contains 1 select input field.

When I select one of the option in the select field. I by default create a section containing text input field, a close button and a Add Field button to add more input text fields.

everything is working just fine but I am not sure how to delete dynamically created input field. I am not sure what to use id or class or name attribute or what to then find and delete the input field when I click on a delete button next to it.

my code

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);

    }

Upvotes: 1

Views: 5760

Answers (2)

zer00ne
zer00ne

Reputation: 43880

If you are using Bootstrap (which you probably are because OP classes are BS), then you are probably using jQuery (BS API requires jQuery). So this Demo is in jQuery. Here's what it does:

  • Starts with 3 buttons +⚙🛦

    • ADD an fieldset.form-group
    • CFG settings (not functional in Demo)
    • SUBmit form data to a live test server
  • Each fieldset.form-group has:

    • 3 <input>

    • 1 <textarea>

    • 2 <button>

      • CFG settings (not functional in Demo)
      • DELete fieldset.form-group
    • Each element with an #id and [name] has a unique suffix (based on Date.now() and Math.random()).

    • Upon SUBmitting form#frm0 a Link is revealed.

      • Clicking the link scrolls the user to iframe#response
      • `iframe#response receives and displays the response from the test server.

References

Template Literals

Demo

// 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);
});
#RSP {
  display: none
}
-
<!DOCTYPE html>
<html lang="en">

<head>
  <title>BS Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>

  <main class="container">

    <form id="frm0" action="https://httpbin.org/post" method='post' target='response'>
      <div class="input-group pull-right">

        <div id='setA' class="btn-group"> <button id='ADD' type="button" class="ADD btn btn-primary"> <i class='glyphicon glyphicon-plus'></i> </button> <button id='CFG' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button>
          <button id='SUB' type="submit" class="SUB btn btn-warning"> <i class='glyphicon glyphicon-send'></i> </button>
        </div>
      </div>
      <fieldset id='setB' class='form-group'>
        <legend>Contact Form</legend>
        <a href='#/' id='RSP' class='btn btn-link'>View Response</a>
      </fieldset>

      <fieldset id='setD' class="form-group"></fieldset>

    </form>

    <iframe srcdoc='<h1 style="text-align:center;font-family:Consolas">Server Response</h1>' src='about:blank' id='response' name='response' frameborder='1' width='99%' height='300'></iframe>

  </main>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>

</html>

Upvotes: 0

plonknimbuzz
plonknimbuzz

Reputation: 2664

you can use closest().

but its only works on modern browser. to hack that you can read here

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

see the example

<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>

Upvotes: 4

Related Questions