Add/remove HTML inside div using JavaScript
Asked Answered
C

10

97

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()">
Carabin answered 15/7, 2013 at 9:23 Comment(2)
Can you post your JavaScript code so far?Eileen
@Eileen I tried following this tutorial: dustindiaz.com/… but didn't get the code to work with my example. I also looked into the updated answer he posted but I didn't really understand the code as I am fairly new to JavaScript.Carabin
G
184

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);
}
Gwyngwyneth answered 15/7, 2013 at 9:29 Comment(7)
I want to be able to add multiple rows. My question was a bit unclear so I edited it.Carabin
This supports multiple rows.Gwyngwyneth
Oh, that's right. Just made a error trying your code. It's working now. Cheers!Carabin
Although, it's not working when wrapping the inputs in a div like <div class="options_part"></div>Carabin
What does javascript look like? Note that you have to put a back slash at the end of each line when setting the innerHTML or else you'll get a syntax error.Gwyngwyneth
Posting a shorted code-snippet. div.innerHTML = '<div class="options_part"><input type="button" value="-" onclick="removeRow(this)"></div>'; And just by removing the div it's working again.Carabin
Oh got ya. You have to remove a child from the parent, so change input.parentNode to input.parentNode.parentNode in removeRow(). A reminder that if you add any more parents to the remove buttons you'll have to change removeRow accordingly like I just did.Gwyngwyneth
D
23

To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).

So using it you would write

function addRow () {
  document.querySelector('#content').insertAdjacentHTML(
    'afterbegin',
    `<div class="row">
      <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)">
    </div>`      
  )
}

function removeRow (input) {
  input.parentNode.remove()
}
<input type="button" value="+" onclick="addRow()">

<div id="content">
</div>
Durga answered 1/8, 2018 at 12:45 Comment(0)
T
6

Another solution is to use getDocumentById and insertAdjacentHTML.

Code:

function addRow() {

 const  div = document.getElementById('content');

 div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');

}

Check here, for more details: Element.insertAdjacentHTML()

Tevis answered 29/1, 2020 at 15:9 Comment(1)
The answer by Hoffmann already covers thisFancy
D
5

I know it took too long, it means you can write more briefly.

    function addRow() {
        var inputName, inputValue, label, checkBox, checked, inputDecrease, content, Ptag;
        // div
        content = document.getElementById('content');
        // P tag
        Ptag = document.createElement('p');
        // first input
        inputName = document.createElement('input');
        inputName.type = 'text';
        inputName.name = 'name';
        // Second input
        inputValue = document.createElement('input');
        inputValue.type = 'text';
        inputValue.name = 'Value';
        // Label
        label = document.createElement('label');
        // checkBox
        checkBox = document.createElement('input');
        checkBox.type = 'checkbox';
        checkBox.name = 'check';
        checkBox.value = '1';
        // Checked?
        checked = document.createTextNode('Checked?');
        // inputDecrease
        inputDecrease = document.createElement('input');
        inputDecrease.type = 'button';
        inputDecrease.value = '-';
        inputDecrease.setAttribute('onclick', 'removeRow(this)')
        // Put in each other
        label.appendChild(checkBox);
        label.appendChild(checked);
        Ptag.appendChild(inputName);
        Ptag.appendChild(inputValue);
        Ptag.appendChild(label);
        Ptag.appendChild(inputDecrease);
        content.appendChild(Ptag);
    }

    function removeRow(input) {
        input.parentNode.remove()
    }
* {
    margin: 3px 5px;
}
<input type="button" value="+" onclick="addRow()">

<div id="content">

</div>
Dyson answered 24/4, 2021 at 20:57 Comment(0)
H
4

You can use this function to add an child to a DOM element.

function addElement(parentId, elementTag, elementId, html) 

 {


// Adds an element to the document


    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}



function removeElement(elementId) 

{

    // Removes an element from the document
    var element = document.getElementById(elementId);
    element.parentNode.removeChild(element);
}
Harv answered 15/7, 2013 at 9:30 Comment(0)
R
2

To remove node you can try this solution it helped me.

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);
Range answered 6/3, 2015 at 10:27 Comment(0)
S
2

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();
Shortie answered 14/10, 2020 at 3:14 Comment(0)
P
1

make a class for that button lets say :

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});
Prepare answered 15/7, 2013 at 9:29 Comment(1)
He didn't mention jQuery.Gwyngwyneth
S
1

please try following to generate

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }
Sonyasoo answered 15/7, 2013 at 9:33 Comment(0)
B
0
<!DOCTYPE html>
<html>
<head>
    <title>Dynamical Add/Remove Text Box</title>
    <script language="javascript">

        localStorage.i = Number(1);

        function myevent(action)
        {
            var i = Number(localStorage.i);
            var div = document.createElement('div');

            if(action.id == "add")
            {
                localStorage.i = Number(localStorage.i) + Number(1);
                var id = i;
                div.id = id;
                div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';

                document.getElementById('AddDel').appendChild(div);
            }
            else
            {
                var element = document.getElementById(action.id);
                element.parentNode.removeChild(element);
            }
        }
    </script>
</head>
<body>
    <fieldset>
    <legend>Dynamical Add / Remove Text Box</legend>
    <form>
        <div id="AddDel">
            Default TextBox:
            <input type="text" name="default_tb">
            <input type="button" id="add" onclick="myevent(this)" value="Add" />
        </div>
            <input type="button" type="submit" value="Submit Data" />
    </form>
    </fieldset>
</body>
</html>
Bicknell answered 15/9, 2019 at 2:27 Comment(2)
Please explain your code a bit for the questioner. :)Corum
In this code we can easily ADD and REMOVE specific Textbox.Bicknell

© 2022 - 2024 — McMap. All rights reserved.