Get an input's "checked" state
I have this basic HTML structure:
<fieldset>
<input/>
<label></label>
<div class="toggle_box">
<div class="switch"></div>
</div>
</fieldset>
I would like this to happen when my input is checked:
<fieldset>
<input checked="checked" />
<label></label>
<div class="toggle_box">
<div class="switch" state="on"></div>
</div>
</fieldset>
开发者_运维问答Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).
Thanks for your brainstorming!
This works; you'll need to add type="checkbox"
to your inputs to make them checkboxes. (Observe the effect by inspecting the switch
div
s with Chrome's Dev Tools or Firebug.)
$('fieldset input[type=checkbox]').change(function() {
var el=$(this).parent().find('.switch');
if ($(this).is(':checked')) el.attr('state','on');
else el.removeAttr('state');
});
You can put all these divs inside another div, and then get the father div with*document.getElementById*, find the div you want in the content and change him.
<div id="fatherOfTheDivs">
<fieldset>
<input/>
<label></label>
<div class="toggle_box">
<div id="div1" class="switch"></div>
</div>
</fieldset>
<fieldset>
<input/>
<label></label>
<div id="div2" class="toggle_box">
<div class="switch"></div>
</div>
</fieldset>
</div>
This will accomplish it for you.
$('input:checkbox').change(function () {
if ($(this).is(':checked')) {
$(this).parent().children('div.toggle_box').children('div.switch').attr('state', 'on');
} else {
$(this).parent().children('div.toggle_box').children('div.switch').removeAttr('state');
}
});
You'll also have to modify your <input />
to <input type="checkbox" />
精彩评论