Determine when a checkbox is unticked and clear a field
I'm trying to detect when a checkbox is un-checked and if the corresponding field below (with an Id) has a value, then empty it.
Any ideas?
I'm working with the following but it isn't working:
$('#end_date_specified').click(function() {
$('#end_date_datepicker, #end_date_datepicker_altfield').empty();
$('#datediv').toggle();
});
开发者_如何学Go
I think one of the problems with this is that it will empty the field values no matter how the checkbox is clicked.
I think this is what you want:
$('#end_date_specified').change(function() {
if(!this.checked) {
$('#end_date_datepicker, #end_date_datepicker_altfield').val('');
}
$('#datediv').toggle(this.checked);
});
Only on change
(better than clicked
to get the right state) we only clear if it's not .checked
, then we show the #datediv
based on whether it's checked (show if it is, hide if it isn't) using .toggle(bool)
.
Right now you are going to be clearing that div no matter what, as you say. What you want to do is check for the "checked" attribute on your check box. If it is false/undefined/null then do the empty.
$('#end_date_specified').click(function() {
if(!$('#end_date_specified').attr('checked')) {
$('#end_date_datepicker, #end_date_datepicker_altfield').empty();
$('#datediv').toggle();
}
});
精彩评论