nsilva
nsilva

Reputation: 5612

Check is checkbox is clicked?

Say for example I have the following:

<input type="checkbox" id="chk-box1" name="chk-box1" value="Check 1">Check 1

<input type="text" id="textbox1" name="textbox1" value="">

I can set the value of the textbox when "chk-box1" is clicked by doing:

$('#chk-box1').change(function(){
    var chk = $(this);
    $('#textbox1').val("Textbox 1 is checked")('selected', chk.attr('checked'));
})

but how could I set the value of the textbox to empty when the box is unchecked? $('#textbox1').val("")

Upvotes: 0

Views: 64

Answers (2)

Adil
Adil

Reputation: 148120

Try this,

Live Demo

if you want to show message instead of true or false.

$('#chk-box1').change(function(){      
    if(this.checked)
         $('#textbox1').val("Textbox 1 is checked");
    else
         $('#textbox1').val("");
})

Upvotes: 3

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using this.checked property

$('#chk-box1').change(function(){
    if (this.checked) {
       $('#textbox1').val("Textbox 1 is checked"); //('selected', chk.attr('checked'));
    } else {
       $('#textbox1').val("");
    }
})

or Simply,

$('#chk-box1').change(function(){
   $('#textbox1').val(this.checked?"Textbox 1 is checked":""); //('selected',     
});

Upvotes: 4

Related Questions