I have a function which creates a DOM element onClick. That Element contains inputs with array names.
At the start I already have one element (the same like those which I create onClick).
<tbody id="elementsBody">
<tr id="element1"> // 1 becomes 2 and so on when new element is added
<td>
<input type="hidden" name="numbers[]" value="1" /> // 1 becomes 2 and so on when new element is added
</td>
<td>
<input type="text" name="titles[]" />
</td>
</tr>
// Newly created Elements goes in here!!!
</tbody>
This is my function which creates more elements like the one above.
And also creates a Delete Button DIV for this newly created element.
function addElement() {
var elementsBody = document.getElementById('elementsBody');
var numbers = document.forms[1].elements['numbers[]'];
var number = numbers.length+1;
if (isNaN(number)) {
var number = 2;
}
var numberInput = '<td><input type="hidden" name="numbers[]" value="'+ number + '" /></td>';
var titleTd = '<td><input type="text" name="titles[]" /></td>';
// This is the Delete Button DIV
// I want to create a function (deleteElement) which Removes This Element
var deleteButton = '<td><div onClick="deleteElement('+ number + ')">Delete Element</div></td>';
elementsBody.insertAdjacentHTML('beforeend', '<tr id="element' + number + '">' + numberInput + titleTd + deleteButton + '</tr>');
}
I want to create a function (deleteElement) which Removes this Added Element onClick.
After Removing an Element, I want that function to reorder all the elements values and ID’s. For example if I remove the Element number 2, the value and ID of the third Element must become 2.
Not JQuery.
Please Help me with that!
Thanks @Esailija for help! Solution (fiddle):