简体   繁体   English

选中和取消选中复选框时切换文本

[英]Toggle text when the checkbox is selected and deselected

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.我无法让 Jquery 响应复选框的状态。

Javascript... Javascript...

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

jQuery... jQuery...

$(function() {
  $("#CheckboxIdHere").click(function() {
    $("#LabelIdHere").html(($(this).is(":checked")) ? "Yes" : "No");
  });
});
$('#myCheckbox').click(function() {
    if($(this).is(':checked')) {
        alert('I have been checked');
        $('#myTextEl').text('Yes');
    } else {
        alert('I have been unchecked');
        $('#myTextEl').text('No');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM