user1843591
user1843591

Reputation: 1136

Javascript cannot select check box

I have a checkbox. I am trying to use the example from another SO question to figure out if it is selected or not.

However, I only seem to be able to query the state of the element using document.getElementById. I would like to get it working as per the Stack Overflow example. Code below...

<html>
<br>
                <label>Select All BOM's</label>
                <input type="checkbox" id="allboms" name="degbutton"/>
<br>


function doSomething()
    {
        //does not work
        if ($("#allboms").checked){
            //Do stuff

            alert('was checked');
        }

        //does not work
        if ($("#allboms").attr("checked")) {

            //Do stuff
            console.log("boooooooooooo");
            alert('i1 was checked');
        }

        //works
        if(document.getElementById("allboms").checked){
            //Do stuff

            alert('is checked ');
       }else{
            alert('is unchecked .....');
       }
</html>

Upvotes: 0

Views: 280

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49188

These are all the forms I can think of using plain Javascript and jQuery:

$(document).ready(function rd(){
    var $allboms = $('#allboms');

    $allboms.on('change', function ch(){
        if (this.checked) {
            console.log('this.checked is true.');
        }

        if ($(this)[0].checked) {
            console.log('$(this)[0].checked is true.');
        }

        if ($(this).prop('checked')) {
            console.log('$(this).prop("checked") is true.');
        }

        if ($(this).is(':checked')) {
            console.log('$(this).is(":checked") is true.');
        }
    });
});

http://jsfiddle.net/dyeu7w77/

Upvotes: 2

user3559349
user3559349

Reputation:

Try

if ($("#allboms").is(':checked')) {
  ..
}

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Try This :-

 if ($("#allboms").is(':checked')){
   .....
 }

Upvotes: 1

Related Questions