user4100421
user4100421

Reputation: 137

change text box text if checkbox is checked

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

Upvotes: 2

Views: 8325

Answers (3)

Guy Lowe
Guy Lowe

Reputation: 2370

Try binding to the click event:

$('input[type=checkbox]').click(function () {
    if ($('input[type=checkbox]').is(':checked')) {
        $('#txt').val('checked');
    }
    else{
        $('#txt').val('unchecked');
    }
});

Upvotes: 3

user2929830
user2929830

Reputation:

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

Upvotes: 0

Seminda
Seminda

Reputation: 1773

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

Upvotes: 2

Related Questions