I am trying to check/uncheck all checkboxes by click on one checkbox in head of table. First click add attribute to inputs, second uncheck. It works only one time. Testing on Firefox and Chrome. Аttributes keep changing, but this is not shown in page. I see it only in browser debugger.
<table>
<thead>
<tr>
<th><input type="checkbox" /></th>
<th>#</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>3</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(function () {
$('th input[type="checkbox"]').click(function(){
if ( $(this).is(':checked') )
$('td input[type="checkbox"]').attr('checked', 'checked');
else
// $('td input[type="checkbox"]').attr('checked', false);
$('td input[type="checkbox"]').removeAttr('checked');
})
});
</script>
Sample http://jsfiddle.net/aJhm9/
Add another click event for checkbox under #checkboxlist , if a checkbox is unchecked then uncheck .
Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.
Use properties instead of attributes
$(function () {
$('th input[type="checkbox"]').click(function(){
if ( $(this).is(':checked') )
$('td input[type="checkbox"]').prop('checked', true);
else
$('td input[type="checkbox"]').prop('checked', false);
})
});
http://jsfiddle.net/aJhm9/2/
.attr()
is for modifying an elements default state only, not its live state Use .prop()
for changing the live state of an element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With