JavaScript:
Here we take advantage of an attribute value selector ([name="how"]
)
the ability to retrieve and set property values. Note too that we iterate through
each of the checkboxes.
To read more about attributes vs properties in jQuery, see: .prop() and .attr()
<form action="http://cscie12.dce.harvard.edu/echo" method="get">
<h3>How did you hear about us?</h3><p>[<a href="#" id="checkall">check all</a>] [<a href="#" id="uncheckall">uncheck all</a>] [<a href="#" id="togglecheckboxes">toggle</a>]</p>
<ul style="list-style: none;">
<li>
<input type="checkbox" name="how" value="radio"/>Radio</li>
<li>
<input type="checkbox" name="how" value="newspaper"/>Newspaper</li>
<li>
<input type="checkbox" name="how" value="magazine"/>Magazine</li>
<li>
<input type="checkbox" name="how" value="online"/>Online</li>
<li>
<input type="checkbox" name="how" value="friend"/>Friend</li>
</ul>
<input type="submit"/>
</form>
In
script
element within head
element (<script type="text/javascript">
):
$(document).ready(function() {
console.log($('#input[name="how"]'));
$('#checkall').click(function() {
$('input[name="how"]').prop('checked',true);
console.log('check all!');
});
$('#uncheckall').click(function() {
$('input[name="how"]').prop('checked',false);
console.log('uncheck all!');
});
$('#togglecheckboxes').click(function() {
$('input[name=how]').each(function (i) {
if ($(this).is(':checked')) {
$(this).prop('checked',false);
} else {
$(this).prop('checked',true);
}
});
});
});
Copyright © David Heitmeyer