I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.
This is my basic HTML structure:
<input type="button" value="+" onclick="addRow()"> <div id="content"> </div>
This is what I want to add inside the content div:
<input type="text" name="name" value="" /> <input type="text" name="value" value="" /> <label><input type="checkbox" name="check" value="1" />Checked?</label> <input type="button" value="-" onclick="removeRow()">
Given an HTML element and the task is to remove the HTML element from the document using JavaScript. Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')
The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document. createElement() method and to create a text node, document. createTextNode() method is used and then this node is appended using appendChild() method.
In your JavaScript program, you can use the “appendChild()” and “insertBefore()” methods for adding the HTML elements and to delete the HTML elements “remove()” and the “removeChild()” methods are invoked.
You can do something like this.
function addRow() { const div = document.createElement('div'); div.className = 'row'; div.innerHTML = ` <input type="text" name="name" value="" /> <input type="text" name="value" value="" /> <label> <input type="checkbox" name="check" value="1" /> Checked? </label> <input type="button" value="-" onclick="removeRow(this)" /> `; document.getElementById('content').appendChild(div); } function removeRow(input) { document.getElementById('content').removeChild(input.parentNode); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With