Someone please help me how to add new function to remove the field, i have js script function th开发者_运维问答at add new field as follows
<script language="javascript">
fields = 0;
function addInput() {
if (fields != 10) {
var htmlText = " <input type='text' name='friends[]' value='' size='auto' maxlength='45' /><br />";
var newElement = document.createElement('div');
newElement.id = 'new_field';
newElement.innerHTML = htmlText;
var fieldsArea = document.getElementById('new_field');
fieldsArea.appendChild(newElement);
fields += 1;
} else {
alert("Only 10 fields allowed.");
document.form.add.disabled=true;
}
}
</script>
but i need some helps to add new functions for removing field, For any suggestion and pointer I Would be appreciate.
Read here about removeChild() function removeChild() - mozilla developer
Edit Or here: removeChild() w3schools
First of all, there's already one problem I see with your code. You are setting each new field's ID to the same value, which is invalid HTML and asking for trouble. Be sure to fix that.
The .removeChild
method of DOM elements is what you want. .removeChild
will remove a node (element or text) from the DOM tree (the set of elements actually contained within the document) only if the node passed in is actually a child of that element, otherwise an error occurs.
You can easily remove the last field by finding the last child of its container:
function removeLastField() {
var fieldsArea = document.getElementById('new_field'),
lastChild = fieldsArea.lastChild;
if(lastChild) {
fieldsArea.removeChild(lastChild);
fields -= 1;
}
}
精彩评论