views:

38

answers:

1

Hi guys , 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.

+1  A: 

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?

WSkid
href="javascript:remove('+divIdName+')"; through this i am calling the function remove().As per your suggestion i changed that remove function still it shows the error my1Div is not defined
Meena
My apologies, it scrolled offscreen and I didn't see it when I skimmed the code. I've updated my answer with another fix for the string/var issue.
WSkid