alireza alizade
alireza alizade

Reputation: 477

How to add an input and remove it if existed with javascript

I have a form and I want to add new input in that and if this input existed remove that or prevent from being added. In my code just added one input and when I try to add another different input first input cleans Body :

<input type="text" id="member" name="member" value="">name<br />
            <a href="#" id="filldetails" onclick="addFields()">add</a>
            <div id="container"/>

footer:

<script type='text/javascript'>
    function addFields(){

        var name = document.getElementById("member").value;

        var container = document.getElementById("container");

        while (container.hasChildNodes()) {
            container.removeChild(container.lastChild);
        }
        for (i=0;i<1;i++){

            container.appendChild(document.createTextNode(name+ (i+1)));

            var input = document.createElement("input");
            input.type = "text";
            input.name = name;
            container.appendChild(input);
            // Append a line break
            container.appendChild(document.createElement("br"));
            container.appendChild(document.createElement("br"));
        }
    }
</script>

Upvotes: 2

Views: 395

Answers (1)

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

You can use querySelector('#member') to check if the input exists or not.

function addFields() {
  var container = document.getElementById("container");
  if (!container.querySelector('#member')) {
    container.innerHTML = `<input type="text" id="member" name="member" value="">name`;
    console.log('input added');
  }
}
<a href="#" id="filldetails" onclick="addFields()">add</a>
<div id="container">

</div>

Upvotes: 1

Related Questions