问题
I want to change text box text depending if checkbox is checked or not. So if the user checks the checkbox, the text box shows some text and if the user unchecked the checkbox, it shows some different text.
HTML:
<input id="check" type="checkbox" />
<input id="txt" type="text" value="aaaa" />
jQuery:
$('input[type=checkbox]').each(function () {
if (!$('input[type=checkbox]').is(':checked')) {
$('#txt').val('checked');
}
else{
$('#txt').val('unchecked');
}
});
JSFiddle Demo
回答1:
Try binding to the click event:
$('input[type=checkbox]').click(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#txt').val('checked');
}
else{
$('#txt').val('unchecked');
}
});
回答2:
It should be like this
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
if ($('input[type=checkbox]').is(':checked')) {
$('#txt').val('checked');
}
else{
$('#txt').val('unchecked');
}
});
});
check the Demo
回答3:
I think the best solution would be to use .change()
and this.checked
like so:
<input id="check" type="checkbox" />
<input id="txt" type="text" value="unchecked" />
$('#check').change(function(){
var checkChange = this.checked ? 'checked' : 'unchecked';
$('#txt').val(checkChange);
});
JSFiddle
来源:https://stackoverflow.com/questions/26171189/change-text-box-text-if-checkbox-is-checked