I have the next code:
js:
$('[id^="check-"]').change(function(){
var new_id = this.id.replace(/check/, 'new'),
real_id = this.id.replace(/check/, 'real');
if ($(this).is(':checked')) {
$('#'+real_id).val($('#'+new_id).text());
} else {
$('#'+real_id).val(0);
}
});
html:
<tr>
<td><span id="new-1">2</span></td>
<td><input type="text" name="real-1" id="real-1" value="0"></td>
<td><input type="checkbox" class="card" id="check-1"></td>
</tr>
<tr>
<td><span id="new-2">7</span></td>
<td><input type="text" name="real-2" id="real-2" value="0"></td>
<td><input type="checkbox" class="card" id="check-2"></td>
</tr>
<tr>
<td><span id="new-3">4</span></td>
<td><input type="text" name="real-3" id="real-3" value="0"></td>
<td><input type="checkbox" class="card" id="check-3"></td>
</tr>
The main idea: take the text from new-* and put it into real-* inbox when you click on related check-* checkbox.
Now I want to add another checkbox that mass executes this operation for all the elements.
I tried it:
$('#main-checkbox').change(function(){
if ($(this).is(':checked')) {
$('.card').attr('checked', true);
} else {
$('.card').attr('checked', false);
}
});
But it does not work. Why?
How can I start the change action for all those checkouts.
Thanks.
Changing field values (including checked status) via JavaScript doesn’t trigger change events, but you can call the
.change()method explicitly. Your function can also be simplified – you don’t really need the if/else structure:Demo: http://jsfiddle.net/4qs4d/
Note that
$(this).is(':checked')is just a slow way of sayingthis.checked. Also, if you are using jQuery 1.6 or later you should use the.prop()method rather than.attr().