ngplayground
ngplayground

Reputation: 21637

jQuery toggle and toggling :checked

I have an input box which is hidden and I am using a span element to change the state of the checkbox but I can't quite figure out how to do it by toggling checked and unchecked.

$('span.volume').click(function(){
    $(this).toggleClass('active');
    $('#mChatUseSound').toggle(); //this needs to toggle :checked
 });


<span class="volume"></span>
<input type="checkbox" id="mChatUseSound" style="display:none;" /></label>

Upvotes: 0

Views: 193

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

DEMO

$('#mChatUseSound').prop('checked',function(){return !this.checked}).change();

As we create a closure, this will refer to specific element in set, here '#mChatUseSound'.

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48982

In this case, if you use <label>, you don't need to write any javascript to toggle checked and unchecked.

<label class="volume" for="mChatUseSound">click</label>
<input type="checkbox" id="mChatUseSound" />

Just need to write script to handle other logic:

$('.volume').click(function(){
    $(this).toggleClass('active');
    //More logic
 });

DEMO

Upvotes: 2

Related Questions