Samuel Samuel - 5 months ago 15
jQuery Question

How do i delete 2 textboxes when i click a button

I have a form whereby users can click on the add button to produce 2 more textboxes at every click. It works perfectly fine until i added in a function name deleterow(). Once i added that function, my addrow() does not work anymore.
This are my codes for addrow().

<button onclick ="addRow()" value="Add Row">Add Row</button>
<button onclick ="deleterow()" value ="Reset">Reset</button>
<script>
var x=1
var count=0;

function addRow()
{

if(count <= 10)
{
var d = document.getElementById('div');
d.innerHTML += "<input type='text' id='txta"+ x +"'><span class =wordtab></span>";
d.innerHTML += "<input type='text' id='txtb"+ x +"'><br><br>";
count++;
x++
}
else
{
alert("Maximum 10 Skills");
}
}


These are my codes for deleterow(). I am also not sure if my codes are correct for deleting 2 'latest' textboxes everytime i click on the delete button.

function deleterow()
{
for(int i=1;i<=10;i++)
{
var element1 = document.getElementById('txta'+i); // will return element
element1.parentNode.removeChild(element1); // will remove the element from DOM
var element2 = document.getElementById('txtb'+i); // will return element
element2.parentNode.removeChild(element2); // will remove the element from DOM
}

}
</script>
<div id="div">


Oh and lastly, how can i do so that everytime i add a new row, my buttons will automatically be below all of the text boxes. Currently, it will be stuck at the top of the page. Thanks!:)

Answer

Because you're using jquery you could use click events instead of inline onclick

I think you should add reset button to every line so you could remove it, for the the add button it will be stuck at the top of the page. you have just to place it after the div.

Check the example bellow, this helps.


var x=1;
var count=0;

$('body').on('click','#add',function(){
  if(count <= 10){
    $('#div').append("<div class='line'><input type='text' id='txta"+ x +"'><span class =wordtab></span><input type='text' id='txtb"+ x +"'><button class='delete' value ='Reset'>Reset</button></div>");
    count++;
    x++
  }
  else
    alert("Maximum 10 Skills");
});

$('body').on('click','.delete',function(){
  $(this).closest('.line').remove(); 
  count--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>
<button id='add' value="Add Row">Add Row</button>