Set checkboxes with jquery

$(document).ready(function(){
    function set_checked {
        alert('test'); 
        $('*:checkbox').attr('checked', checked);
    }
}); 

And this html

<input onclick="set_checked()" value="Check all" type="button" />

Not working for some reason. There is no notification window or nothing.

+1
source share
8 answers

You have a few problems

  • missing parentheses in function definition set_checked
  • undefined variable checked
  • onclick refers to a global function that is not global.

With jQuery, it's better to add a click event to an element using the jQuery method click. Here's how to do it with jQuery.

$(document).ready(function(){
    // If you want to use the `set_checked` function elsewhere do this
    function set_checked() {
        $('*:checked').attr('checked', true);
    }
    $('#check_all').click(set_checked);

    // If you are only doing `set_checked` on the button press do this
    $('#check_all').click(function() {
        $('*:checked').attr('checked', true);
    });
});

<input id="check_all" value="Check all" type="button"/>
+4
source
$('*:checkbox').attr('checked', checked);

apparently resolved as

$('*:checkbox').attr('checked', undefined);

You must have

$('*:checkbox').attr('checked', 'checked');
+3
source

:

function set_checked() {
        alert('test'); 
        $('*:checkbox').attr('checked', 'checked');
    }

()

: , .

+2

javascript:

function set_checked() {
    alert('test');
    $('input:checkbox').attr('checked', 'checked'); 
}

, .

EDIT: . .

0

. () set_checked {.

0

: $(document).ready();, , .

Update:

, jQuery .

HTML:

<p><input id='test' type='submit' value='Click me' onclick='checkAll();' /></p>
<p>Let see:</p>
<ul>
    <li><input type='checkbox'></li>
    <li><input type='checkbox'></li>
    <li><input type='checkbox'></li>
</ul>

JavaScript:

$(document).ready(function () {
    $('#test').click(function (event) {
        $('input[type="checkbox"]').attr('checked', 'checked');
    });
});

.

0

:

  $(document).ready(function(){
    function set_checked {
        alert('test'); 
        $('*:checkbox').attr('checked', checked);
    }
 }); 

:

function set_checked() {
    alert('test'); 
    $('*:checkbox').attr('checked', 'checked');
}

As already mentioned, you need to () define the definition of the function and the quotation marks around "checked", but you also need the function defined in the global scope, therefore not inside the jquery onready handler.

0
source

You defined the set_checked function inside the function, which means that it is not in the global scope and cannot be accessed when an input event occurs.

0
source

All Articles