1

I have a simple js code, but it doesn't work (no alert when checking the checkbox) what is the prob? :

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        checkbox.onclick = "openFiles()";            
}

function openFiles() {
    alert("hey");
}

2 Answers 2

2

Simply assign the function itself, not a string:

checkbox.onclick = openFiles;

Full example:

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        checkbox.onclick = openFiles;
        
        document.body.appendChild(checkbox);
}

function openFiles() {
    alert("hey");
}

dynamicCheckbox();

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could help ;)
1

You can add event handle to dynamic control as

document.addEventListener('click',function(e){
       if(e.target && e.target.id== 'chkid'){
            openFiles();
       }
});

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        //checkbox.onclick = "openFiles()";
        document.addEventListener('click',function(e){
          if(e.target && e.target.id== 'chkid'){
            openFiles();
         }
        });
        
        document.body.appendChild(checkbox);
 
}

function openFiles() {
    alert("hey");
}

dynamicCheckbox();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.