Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a checkbox to toggle another element?

Tags:

jquery

How can I check 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?

like image 831
Karem Avatar asked Sep 04 '10 16:09

Karem


2 Answers

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');
});
like image 181
Harmen Avatar answered Nov 15 '22 21:11

Harmen


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/

like image 35
user113716 Avatar answered Nov 15 '22 22:11

user113716