Toggle Text

I have a checkbox with text next to it. I want to switch the text "YES" or "NO" when the checkbox is checked and unchecked. It's hard for me, does anyone have an example? I cannot get jQuery to respond to the state of the checkbox.

thanks

+3
source share
2 answers

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");
  });
});
+9
source
$('#myCheckbox').click(function() {
    if($(this).is(':checked')) {
        alert('I have been checked');
        $('#myTextEl').text('Yes');
    } else {
        alert('I have been unchecked');
        $('#myTextEl').text('No');
    }
});
+3
source

Source: https://habr.com/ru/post/1711206/


All Articles