开发者

How do I use a checkbox to toggle another element?

How can I c开发者_开发问答heck if my checkbox with an id of UseUsername has been checked, and then use that information to toggle another element with an id of div?


It's as easy as:

$('#UseUsername').change(function(){
  if($(this).is(':checked')){
    $('#div').show();
  } else {
    $('#div').hide();
  }
});

Additionally, you could fire this event when the page loads, so the div will disappear if the checkbox isn't checked.

// Show the div only if the checkbox is checked
function toggleDiv(){
  if($(this).is(':checked')){
    $('#div').show();
  } else {
    $('#div').hide();
  }
}

$(document).onload(function(){

  // Set change event to hide/show the div
  $('#UseUsername')
    .change(toggleDiv)
    .trigger('change');
});


A very simple way would be like this:

$('#UseUsername').change(function(){
    $('#div').toggle(this.checked);  // show if it is checked, otherwise hide
});

Try it: http://jsfiddle.net/mHNuN/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜