vendredi 8 septembre 2017

jQuery checkbox always false

First off I'd like to say that I know that this question was already asked a lot of times but I can assure you that I tried using all the answers I could find but all failed.

So first off I have a jQuery Datatable looking like this (I'm using laravel so that's why there's this foreach) :

<table>
    <thead>
        <tr>
            <th id="head-cbx"><input type="checkbox" name="example"></th>
            <th id="head-xcode">XCODE</th>
        <tr>
    </thead>
    <tbody>
    @foreach($xcodes as $xcode)
        <tr>
            <td id="head-cbx"><input type="checkbox" class="xcode-cbx" name="xcodes[]"></td>
            <td></td>
        <tr>
    @endforeach
    </tbody>
</table>

The obvious objective is to have a checkbox that allows me to check / uncheck all the others.

For the jQuery part I tried the following solutions :

$(document).ready(function(){
    var headcbx = $('#head-cbx');
    headcbx.change(function(){
    if (headcbx.is(':checked')) {
            //uncheck all
        } else {
            //check all
        }
    });
}

then

$(document).ready(function(){
    var headcbx = $('#head-cbx');
    headcbx.change(function(){
    if ($(this).is(':checked')) {
            //uncheck all
        } else {
            //check all
        }
    });
}

then

$(document).ready(function(){
    var headcbx = $('#head-cbx');
    headcbx.change(function(){
    if (this.is(':checked')) {
            //uncheck all
        } else {
            //check all
        }
    });
}

then I changed my test from

if (this.is(':checked'))...

to

if(this.checked)

and then to

if(this.prop('checked)

of course, each time I tried the variants

this
headcbx
$(this)
$('#head-cbx')

After that I tried using

$(document).on('change', '#head-cbx', function(){...})

with all the same variants that I listed above.

Anyway, I always have the same result : false. So I'm beginning to get frustrated and I could use the help because I think I'm missing something obvious somewhere but I can't seem to find it...

Thanks :)

Aucun commentaire:

Enregistrer un commentaire