Note that there are some explanatory texts on larger screens.

plurals
  1. POdynamically remove form elements using javascript
    text
    copied!<p>I want to dynamically remove form elements using javascript. The code below is simple and dynamically adds form elements.</p> <p>My form looks like (sorry, tried to get it working in jsfiddle but couldn't. Definitely works on my own servers though):</p> <p>"first name" "last name" "age"<br> Add more data (button) Submit (button)</p> <p>If you click on Add more data you get</p> <p>"first name" "last name" "age" <br> "first name" "last name" "age" "remove (button)"<br> Add more data (button) Submit (button)</p> <p>I record every new row via fooID+x+i. Eg the first time you add form element "first name" would be referenced as "foo10", "last name" will be "foo11" and so forth.</p> <p>How do I fix the below to dynamically remove form elements that are being clicked on to be removed?</p> <pre><code>&lt;script language="javascript"&gt; function removeRow(r) { /********************* Need code in here *********************/ } &lt;/script&gt; var x = 1; function add() { var fooId = "foo"; for (i=1; i&lt;=3; i++) { //Create an input type dynamically. var element = document.createElement("input"); //Assign different attributes to the element. element.setAttribute("type", fooId+x+i); element.setAttribute("name", fooId+x+i); element.setAttribute("id", fooId+x+i); if(i==1){ element.setAttribute("value", "First name"); } if(i==2){ element.setAttribute("value", "Last name"); } if(i==3){ element.setAttribute("value", "age"); } var foo = document.getElementById("fooBar"); foo.appendChild(element); foo.innerHTML += ' '; } i++; var element = document.createElement("input"); element.setAttribute("type", "button"); element.setAttribute("value", "Remove"); element.setAttribute("id", fooId+x+i); element.setAttribute("name", fooId+x+i); element.setAttribute("onclick", "removeRow(this)"); foo.appendChild(element); var br = document.createElement("br"); foo.appendChild(br); x++; } &lt;/SCRIPT&gt; &lt;body&gt; &lt;center&gt; &lt;form id="form" name="form" action="test.php" method="post" enctype="multipart/form-data"&gt; &lt;input type="text" id="foo01" name="foo01" value="first name"&gt; &lt;input type="text" id="foo02" name="foo02" value="last name"/&gt; &lt;input type="text" id="foo03" name="foo03" value="age"&gt; &lt;br&gt; &lt;span id="fooBar"&gt;&lt;/span&gt; &lt;FORM&gt; &lt;INPUT type="button" value="Add more data" onclick="add()"/&gt; &lt;input type="submit" value="Submit"&gt; &lt;/center&gt; &lt;/FORM&gt; &lt;/form&gt; &lt;/body&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload