Ad

Add/remove Fields Missing Id's

- 1 answer

I'm having some trouble with my add/remove fields code.

If I run this code in phpfiddle and I make extra fields with the adding button.

<script>
                 var i = 1;
        function addKid(){
            if (i <= 5){
                i++;
                var div = document.createElement('div');
                div.style.width = "600px";
                div.style.height = "50px";
                div.style.color = "white";
                div.setAttribute('class', 'myclass');
                div.innerHTML = 'Child : <input type="text" name="child_v.innerHTML = 'Child : <input type="text" name="child_'+i+'" > Ages : <input type="text" name="ages_'+i+'"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';

                document.getElementById('kids').appendChild(div);
                }
                }
                function removeKid(div) {
                    document.getElementById('kids').removeChild( div.parentNode );
                    i--; }
</script>




      <div id="kids">
                    Child : <input id="child_1" type="text" name="child_'+i+'">
                   Ages :  <input id="ages_1" type="text" name="ages_'+i+'">
                   <input type="button" id="add_kid()" onClick="addKid()" value="+" />
                </div>

Then if I use firebug on the first fields I get this.

<input id="child_1" type="text" name="child[]">
<input id="ages_1" type="text" name="ages[]">

On my extra added fields I get this with firebug.

<input type="text" name="child_2">
<input type="text" name="ages_2">

I'm missing id's and how can I add id's to the extra added fields like this.

<input id="child_2" type="text" name="child_2">
<input id="ages_2" type="text" name="ages_2">

If I can make up 5 extra fields with the button, how can they each get a id like this.

<input id="child_3" type="text" name="child_3">
<input id="ages_3" type="text" name="ages_3">
.
<input id="child_4" type="text" name="child_4">
<input id="ages_4" type="text" name="ages_4">
.
<input id="child_5" type="text" name="child_5">
<input id="ages_5" type="text" name="ages_5">
Ad

Answer

In your addKid() loop you are not specifying an ID for each of the newly appended children. To get this working amend the innerHTML line to include the id:

div.innerHTML = 'Child : <input id="child_'+i+'" type="text" name="child_'+i+'" > Ages : <input id="ages_'+i+'" type="text" name="ages_'+i+'"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';

Now your newly created elements will have an ID appended to them too.

Ad
source: stackoverflow.com
Ad