views:

123

answers:

2
+3  Q: 

Toggle text

I have a check box with text next to it. I want to toggle the text 'YES' or 'NO' when the checkbox is selected and deselected. I am having a hard time with this, does anyone have an example of this? I can't get Jquery to respond to the state of the checkbox.

Thanks

+9  A: 

Javascript...

window.onload = function() {
  var chk = document.getElementById('CheckboxIdHere')
  chk.onclick = function() {
    var lbl = document.getElementById('LabelIdHere')
    lbl.innerHTML = (this.checked) ? "Yes" : "No";
  }
}

jQuery...

$(function() {
  $("#CheckboxIdHere").click(function() {
    $("#LabelIdHere").html(($(this).is(":checked")) ? "Yes" : "No");
  });
});
Josh Stodola
Thanks, worked great.
Tony Borf
+3  A: 
$('#myCheckbox').click(function() {
    if($(this).is(':checked')) {
        alert('I have been checked');
        $('#myTextEl').text('Yes');
    } else {
        alert('I have been unchecked');
        $('#myTextEl').text('No');
    }
});
karim79