I wrote a simple script that add extra form fields when needed by the user: the html part consist of a first section where I define a form field pattern and a second part, ready for the insertion of the pattern.
<div id="readroot" style="display: none">
<input type="text" value="test" id="name" name="name">
</div>
<form method="post" action="index.php">
<span id="writeroot"></span>
<a href=# onclick="moreFields();">Add record</a>
<input type="submit" value="Confirm" />
</form>
The javascript part would have to exactly replicate the “readroot” div just before the “writeroot” span. It replicates everything, indeed, except the “name”, “id”, value” of the input fields (or, maybe, I’m not able to handle them). I also tried putting an onclick to detect the field name after it’s been “placed”, but it doesn’t return the correct name!!!
<script type="text/javascript">
var counter = 0;
window.onload = moreFields();
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = 'baba';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name;
if (theName)
newField[i].name = theName + counter;
newField[i].onclick = alert(this.name);
}
var insertHere = document.getElementById('writeroot');
inserted = insertHere.parentNode.insertBefore(newFields,insertHere);
}
</script>
Thank you in advance!
Your are setting the
clickevent handle the wrong way. You are callingalertimmediately and in this context ,thiswill refer to thewindowobject.It should be:
Seems to work fine for me: http://jsfiddle.net/2KSds/
The
nameof the input field is correctly changed and the id is there. If you add the element more that one time you also have to change thebabaid and thenameid to something unique.The question is whether you need the IDs at all. Do you have to uniquely identify the fields? Using classes might be sufficient. Something like:
and
You can then control the visibility through setting CSS rules for
.fieldContainer.