Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery button to uncheck checkboxes [duplicate]

This task seemed to be very easy, though my code doesn't work.

I have table with some rows, each row has a checkbox, underneath I put button "Remove all" to uncheck checkboxes.

This is my code:

    $('#remove-button').click(function(){
        $('input:checked').prop('checked',false);
        //e.stopPropagation(); // I tried also with this
        // $('input:checked').removeAttr('checked'); // or this syntax
    });

When i click on the button, all inputs are unchecked but this is not happen due to my code because when I comment this snippet, it also happens when I click on the button. I also see that when I click and inputs are unchecked my website seems to refresh because page scrools up.

I also add another button to checked inputs:

    $('#add-button').click(function(e){
        $('input').prop('checked',true);
        //e.stopPropagation(); // I tried also with this
        // $('input:checked').removeAttr('checked'); // or this syntax
    });

When I fire this inputs are checked and in a second my website refreshes and everything disappear.

I use the newest Firefox and Chrome, and jQuery - 1.11 (but checked also with 1.8.0 and 1.7.1).

There is also atatched

Anyone knows what is wrong?

like image 357
kuba0506 Avatar asked Aug 01 '14 05:08

kuba0506


1 Answers

'checked' property is boolean but it means when it not exists it is false. If you need not submit on click or don't go to link there is e.preventDefault(). So you need this:

 $('#remove-button').click(function(e) {
    $('input:checked').removeAttr('checked');
    e.preventDefault();
 });
 $('#add-button').click(function(e) {
   var input = $('input.input-to-check')
   input.attr('checked', 'checked');
   e.preventDefault();
 });
like image 112
Lyubimov Roman Avatar answered Oct 28 '22 16:10

Lyubimov Roman