Unable to remove the textbox using JavaScript
I am facing a problem with removing the textbox using JS. I am using below mentioned code:
<html>
<head>
<script language=javascript>
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1 + 2);
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = '<input type=text id=' + num + ' value=' + num + '><a href="javascript:remove('+divIdName+')">Remove</a>';
ni.appendChild(newdiv);
}
function remove(dId) {
var ni = document.getElementById('myDiv');
ni.removeChild(dId);
}
</script>
</head>
<body>
开发者_如何学运维<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:addElement()" >Add TextBox</a></p>
<div id="myDiv"></div>
</body>
</html>
This code is working fine without the html header !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
If i add this header to the code and remove link is not working . Whats problem with that code?
The method .removeChild
only applies to parent nodes and its direct children.
Instead you can use a more general purpose remove function that automatically selects the parent.
function remove(dId){
var rem = document.getElementById(dId);
rem.parentNode.removeChild(rem);
}
Edit:
Another issue is the innerHTML of the remove anchor. It needs to send a string and its trying to send a variable.
newdiv.innerHTML = '<input type=text id=' + num + ' value=' + num + '><a href="javascript:test(\''+divIdName+'\')">Remove</a>';
The existing code worked in IE8 and Chrome but failed in FF. This function works in all three, but I'm a little lost on why exactly... looking in firebug it shows the same DOM structure, maybe someone else could clarify?
精彩评论