Reputation: 23
I am trying to code an easy way to check and uncheck form checkboxes with jQuery. I have tried some of the examples found in stackoverflow, but my limited JS knowledge is keeping me from getting results.
Here is my code, and it is not changing the input checkboxes to "checked" as I intended, i also included a button to clear the selection, but JS still does not reference it.
HTML:
<section id="opzioni">
<div class="bottoni-toggle">
<!-- toggle button -->
<input id="#select-all" type="button" value="Tutti" title="Toggle">
<!-- clear button -->
<input id="#select-none" type="button" value="Nessuno" title="Clear">
</div>
<div class="col_opt">
<span class="custom_chb_wrapper">
<span class="custom_chb">
<input class="bottone-opzioni" id="_4wd" name="_4wd" type="checkbox">
<input id="_4wd" name="_4wd" type="hidden" value="0">
</span>
<label>4WD</label>
</span>
</div>
<div class="col_opt">
<span class="custom_chb_wrapper">
<span class="custom_chb">
<input class="bottone-opzioni" id="_airbag" name="_airbag" type="checkbox">
<input id="_airbag" name="_airbag" type="hidden" value="0">
</span>
<label>Airbag</label>
</span>
</div>
jQuery:
$(document).ready(function() {
$("#select-all").click(function() {
var checkBoxes = $("input.bottone-opzioni");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
Here is the fiddle I set up to test: Hope you can help.
Upvotes: 2
Views: 1727
Reputation: 413
You had a mistake in your HTML. Don't include # when declaring an elements ID
e.g
this is incorrect:
<input id="#select-all" type="button" value="Tutti" title="Toggle">
this is correct
<input id="select-all" type="button" value="Tutti" title="Toggle">
$(document).ready(function() {
$("#select-all").click(function() {
var checkBoxes = $("input.bottone-opzioni");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
$("#select-none").click(function() {
var checkBoxes = $("input.bottone-opzioni");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
Upvotes: 1
Reputation: 22395
Your jQuery is fine, your HTML however, is wrong.
http://jsfiddle.net/82hLvvtt/1/
You have a #
in the HTML id, which is not needed like a jQuery selector. Just remove it.
<input id="select-all" type="button" value="Tutti" title="Toggle">
<!-- clear button -->
<input id="select-none" type="button" value="Nessuno" title="Clear">
Upvotes: 5