vendredi 21 août 2015

Accurately detecting checkbox state everytime with jQuery

Simply put: How can I use jQuery to detect a checkbox state reliably.

I have seen several versions of this question and most find a solution that works for them, in that scenario. However, none seem to work for me in this (seemingly straightforward) situation.

I have created 5 separate (but pretty similar) versions of the detection script. One works, but is too specific to be useful (works off ids for each chkbox) and the other 4 either detect both as checked, or both as unchecked.

I'd rather stick with jQuery to keep the code readable by all the other people working on this project (variety of JS levels), but if it is JS only then I guess that's better than it not working at all!

HTML (basically default Bootstrap3 inline-checkboxes);

<form>
    <p>Do you have a password?</p>
    <fieldset class="inline">
        <label for="radio-inline-1" class="block-label">
            <input checked="checked" type="radio" value="no" name="radio-inline-group" id="radio-inline-1">
            No, I want to create a password now
        </label>
        <label for="radio-inline-2" class="block-label">
            <input autocomplete="off" type="radio" value="yes" name="radio-inline-group" id="radio-inline-2">
            Yes, I already have a password
        </label>
    </fieldset>
</form>

The JavaScript / jQuery

//Both detected as unchecked
$('.block-label input').each(function(){
        //checked 
    } else {
        //unchecked;
    }
});

//or if I want them both detected as checked
$('.block-label input').each(function(){
    if ($('.block-label input:checked').length > -1) {
        //checked
    } else {
        //unchecked
    }
});

//back to unchecked for prop
$('.block-label input').each(function(){
    if ($('.block-label input').prop('checked') === 'checked') {
        //checked
    } else {
        //unchecked
    }
});

//but strangely checked for attr
$('.block-label input').each(function(){
    if ($('.block-label input').attr('checked') === 'checked') {
        //checked            
    } else {
        //unchecked               
    }
});

//vanilla, ultra specific, JS to check that it IS actually possible to detect the state
var chkBox1 = document.getElementById('radio-inline-1');
var chkBox2 = document.getElementById('radio-inline-2');
if (chkBox1.checked) {
        //checked
} else {
        //unchecked
}
if (chkBox2.checked) {
        //checked
} else {
        //unchecked
}

I have put all of these methods in a fiddle and attached them to buttons for ease, but the real function has to run directly after the DOM has loaded (document.ready): http://ift.tt/1JaicNI




Aucun commentaire:

Enregistrer un commentaire