2

i built two buttons with this values("+" and "-") when i click on "+" it creates a text and combo box, i wanna know how to remove them with "-" button?(by only JavaScript)

here's the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>create and delete</title>
<script type="text/javascript">
/*this function creates text box and combo box*/
function cre()
    {var t=document.createElement('select');
    var form=document.getElementById('theForm');
    var label = document.createElement('label');
    var textbox = document.createElement('input');
    form.appendChild(t);
    form.appendChild(textbox);}
function del()
    /*{delete t,form,label,textbox;}*/
</script>
</head>
<body>
    <form id='theForm'>
        <input type="button" value="+" onclick="cre()" />
        <input type="button" value="-" onclick="del()" />
    </form>
</body>
</html>
hamid reza
  • 45
  • 1
  • 8

2 Answers2

1
    function del()
        {
        var form=document.getElementById('theForm');
        var t = form.getElementsByTagName('select');
        var textbox = form.getElementsByTagName('input');
        if(t != 'undefined' && textbox != 'undefined')
        {
            form.removeChild(t[t.length-1]);
            form.removeChild(textbox[textbox.length-1]);
        }
        }

Fiddle for your reference

Prasath K
  • 4,950
  • 7
  • 23
  • 35
1

My solution :

cre = function() {
    var form = document.getElementById('theForm'),
        div = document.createElement('div'),
        t = document.createElement('select'),
        label = document.createElement('label'),
        textbox = document.createElement('input');

    div.className = 'divContainer';
    div.appendChild(t);
    div.appendChild(label);
    div.appendChild(textbox);
    form.appendChild(div);
}

/*{delete t,form,label,textbox;}*/
delForm = function() {
    var form = document.getElementById('theForm');
    form.parentNode.removeChild(form);
}

del = function() {
    var containers = document.getElementsByClassName('divContainer');
    for(var i = 0; i < containers.length; i++) {
         if(typeof(containers[i]) === 'object') {
             containers[i].parentNode.removeChild(containers[i]);
         }
     }
}

JSFiddle : http://jsfiddle.net/j6Fxc/27/

EpokK
  • 38,062
  • 9
  • 61
  • 69