简体   繁体   中英

Checking if dynamically created checkbox is selected using javascript

I have a table containing checkboxes. I add checkboxes to a table whenever a button is clicked as follows:

    var cell3 = row.insertCell(2);
    cell3.innerHTML = '<input type="checkBox" value=\"selected?\" style="cursor:pointer" value="htcb"/>';

How can I find out if the checkbox in, say cell 3, is selected?

I've tried this

var myCheckBox = row.cells[2].innerHTML;
   if(myCheckBox .checked == true)
      //

but it doesn't work

The innerHTML property is just a string, you need to access the DOM object itself.

Seeing as the <input> is the only thing in the cell, this should work:

var myCheckBox = row.cells[2].firstChild;
if (myCheckBox.checked) {
    ...
}

js function:

function check() {
     if($(this).is(”:checked”))
     {
         alert(’checked’);
     }
}

you must add onchange listener:

cell3.innerHTML = '<input type="checkBox" value=\"selected?\" 
               style="cursor:pointer"value="htcb" onchange="check()"/>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM