Evan M. Rose Evan M. Rose - 4 months ago 19
HTML Question

Javascript Complete Amateur?

I have a javascript function I wrote to append a select box to a radiobutton set based on which radio button is clicked. It does this when one clicks one or the other. The problem is, I'm such an amateur that I can't get it to stop adding new select elements to the span I set to place them in. I keep trying different ways to check if the element or its innerHtml have been set and then use that check to decide whether to create another select. None of this has worked for me. Can anyone point me in the direction of a tutorial for this (i've been searching, tried nearly everything, no fez which makes me think its a simpler problem with the structure of the whole function).

Here is the code, any light shed on this would be SUPER helpful. I just taught myself to code so I know this is horrible. Thanks for the help!!

function moreInput(vInput) {
var moreD = document.getElementById('moreD');
//document.write(moreD);
if(vInput == \"approved\") {
if(moreD.length > 0) {
moreD.removeChild(approvedOpts);
}
var select = document.createElement(\"select\");
select.options[0] = new Option('a');
select.options[1] = new Option('b');
select.options[2] = new Option('c');
select.setAttribute(\"name\",\"approvedOptsA\");
}
if(vInput == \"denied\") {
//alert(moreD.innerHtml);
//if(moreD.innerHtml === 'undefined') {
//moreD.removeChild(approvedOptsD);
var select = document.createElement(\"select\");
select.options[0] = new Option('x');
select.options[1] = new Option('y');
select.options[2] = new Option('z');
select.setAttribute(\"id\",\"approvedOptsD\");
select.
//}
}
moreD.appendChild(select);


}

Answer

Remove all elements before you add any new elements.

This code should work:

<script type=\"text/javascript\">

function moreInput(vInput)  {
    var moreD = document.getElementById('moreD');
        if(vInput == \"approved\")  {
            removeAllChildrens(moreD);
            var select = document.createElement(\"select\");
            select.options[0] = new Option('Comped Table');
            select.options[1] = new Option('Comped Drink');
            select.options[2] = new Option('Comped Cover');
            select.setAttribute(\"name\",\"approvedOptsA\");
        }
        if(vInput == \"denied\")    {
                removeAllChildrens(moreD);
                var select = document.createElement(\"select\");
                select.options[0] = new Option('Need to Reserve Table');
                select.options[1] = new Option('At Capacity');
                select.options[2] = new Option('Private Event');
                select.setAttribute(\"id\",\"approvedOptsD\");
        }
    moreD.appendChild(select);
}

function removeAllChildrens(cell) {
    if ( cell.hasChildNodes() ) {
        while ( cell.childNodes.length >= 1 ) {
            cell.removeChild( cell.firstChild );       
        } 
    }
}

 </script>
Comments