jeudi 24 mars 2016

I need to code addEventListener inside a function and that function gets executed everytime a checkbox is checked

What is want: There is a checkbox, whenever it is checked, an input box is added and whenever unchecked that input box gets deleted.

It is happening if i code it in a JavaScript not within a function.

If i keep it within a function and call that function as a onChange event in the html it behaves in a different way.

Javascipt:

var chkboxalbum=document.getElementById("chknewalbum");
    chkboxalbum.addEventListener("change",function(){
             "use strict";
        if(document.getElementById("albumpic"))
        {
            document.getElementById("albumpic").remove(); 
        }
        else
        {                           
            var input12 = document.createElement("input");
            input12.className='w3-input w3-border';
            input12.id='albumpic';
            input12.name='albumpic';
            input12.type='file';
            input12.style='width:70%; display:inline';
            var ptag=document.createElement("p");
            ptag.id='ptag';
            ptag.appendChild(input12);

            var anchorr=document.getElementById("songname");
            anchorr.parentNode.insertBefore(ptag,anchorr);      

            }           
    });

HTML:

<p><input class="w3-check" id="chknewalbum" name="chknewalbum" type="checkbox"><label class="w3-validate">New Album?</label></p>

I want to add a onchange attribute to the HTML and want to keep the above javascript in a function. How to do that ?




Aucun commentaire:

Enregistrer un commentaire