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 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?
链接地址: http://www.djcxy.com/p/89026.html上一篇: 为什么XHTML1.1在* XHTML1.0之前的日期*? 今天什么是首选的XHTML?
下一篇: 无法使用JavaScript删除文本框