Asked
Updated
Viewed
44.3k times

I need to add elements dynamically to a Form in JavaScript. I thought the addChild method would be useful and I tried the following:

var objForm = document.getElementById("idForm");
objForm.addChild(element);

However, it produces an error saying the object doesn't have the method.

How can I add elements to a form using Javascript?

add a comment
1

2 Answers

  • Votes
  • Oldest
  • Latest
JO
184 4
Answered
Updated

Try this on for size 😁

I tested this in multiple browsers:

<html>
<head>
<title>Adding elements to a form</title>
<script>
let items = 1;
function AddItem() {
    let div = document.getElementById("items");
    let button = document.getElementById("add");
    items++;

    let newitem="<b>Item " + items + ": </b>";
    newitem += "<input type=\"text\" name=\"item" + items;
    newitem += '" size="45"><br>';
    newnode = document.createElement("span");
    newnode.innerHTML = newitem;
    div.insertBefore(newnode,button);
}
</script>
</head>
<body>
    <h1>Adding Form Elements</h1>
    <p>The form below allows you to add elements dynamically.</p>
    <hr>
    <form name="form1">
        <div ID="items">
            <b>Item 1:</b>
            <input type="text" name="item1" size="45">
            <be>
            <input type="button" value="Add an Item" onClick="AddItem();" ID="add">
        </div>
    </form>
</body>
</html>

If you add a group of checkboxes or something of the sort you may want to make every dynamically created element have the same ID so you can access them through an array 😉

add a comment
1
Answered
Updated

My code is something like this. I've checked that in the copyForm function all the elements of objSourceForm are copied into newElement variable. My problem is that I don't know how I can add it to objTargetForm (the commented line):

function myFunction () {
    var objForm1 = document.getElementById("idForm1");
    var objForm2 = document.getElementById("idForm2");
    copyForm (objForm1, objForm2);
    objForm2.submit();
}

function copyForm(objSourceForm, objTargetForm) {
    var num = objSourceForm.elements.length;
    var objSource;
    for (var i = num -1 ; i >= 0; i--) {
        objSource = objSourceForm.elements[i];
        if ((objSource.type != "button")&&(objSource.type != "submit")) {
            var newElement = objSource.cloneNode(true);
            //how can I add newElement to objTargetForm?
        }
    }
}
add a comment
0