简体   繁体   中英

how to select / unselect the checkboxes using javascript/jquery

I have the following html code

html code

<p><a href="" onclick="select()">Select All</a>&nbsp; / &nbsp;<a href="" onclick="unselect()" >Unselect All</a> </p>

{% for field in fields %}
  <div class="contact_align">    
    <input id="select-unselect" type="checkbox" name="invite" value="so">{{ field }}
  </div>
{% endfor %}

<script type="text/javascript">
    function select(){
                $('#select-unselect').attr('checked',true);
            }
    function unselect(){
                $('#select-unselect').attr('checked',false);
            }               
</script>

so above is my code, and the functionality is not working , so can anyone please let me know what i am doing wrong in the above code and make it work ?

use .prop(), also since you have multiple elements with the same id use class instead of id

<input class="select-unselect" type="checkbox" name="invite" value="so">{{ field }}

Then

$('.select-unselect').prop('checked',true);

You need to add a return false in your functions. Otherwise the a tags are just behaving as normal a tags and thus going to the href specified. And change the attr(...) for prop(...) .

function select(){
    $('#select-unselect').prop('checked',true);
    return false;
}

function unselect(){
    $('#select-unselect').prop('checked',false);
    return false;
}

Or toggle it in one function like this:

function select(){
    $('#select-unselect').prop('checked',function(id,checked){ return !checked; });
    return false;
}

But I would recommend changing the id #select-unselect to a class .select-unselect because you can't have duplicate ids.

Also change <input id="select-unselect" type="checkbox" name="invite" value="so">{{ field }} to <input class="select-unselect" type="checkbox" name="invite" value="so">{{ field }}

Use Prop instead of attr. Please see this link Jquery Attr to see the difference between attr and prop.
$('#select-unselect').prop('checked',true);

And try to use class instead of id of a control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM