change text box text if checkbox is checked

浪子不回头ぞ 提交于 2019-12-24 03:43:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!