Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only show input fields if checkbox is checked?

Basically, I want to only show these fields if checkbox is selected, if it becomes unselected, disappear.

<input type="checkbox" name="supplied" value="supplied" class="aboveage2" />

<ul id="date">
    <li><input id="start" name="start" size="5" type="text" class="small" value="1" /></li>
    <li><input id="end" name="end" size="5" type="text" class="small" value="2" /></li>
</ul>

I've tried something like:

$('#supplied').live('change', function(){
     if ( $(this).val() === 'supplied' ) {
         $('.date').show();
     } else {
         $('.date').hide();
     }
 });

Any advice would be greatly appreciated =)

like image 839
Latox Avatar asked Feb 28 '11 01:02

Latox


2 Answers

The "#foo" selector looks for elements whose id value is "foo", not "name". Thus the first thing you need to do is add an "id" attribute to your checkbox.

The second thing to worry about is the fact that, in IE (at least old versions), the "change" event isn't fired until the checkbox element loses focus. It's better to handle "click", and what you want to check is the "checked" attribute of the element.

What I'd write is something like:

$('#supplied').click(function() {
  $('.date')[this.checked ? "show" : "hide"]();
});
like image 65
Pointy Avatar answered Sep 21 '22 16:09

Pointy


Pointy pointed out that you need to set the id of our checkbox (or use a name selector). You also need to use #date (id) instead of .date (class) (or again change the HTML).

Working demo

like image 37
Matthew Flaschen Avatar answered Sep 18 '22 16:09

Matthew Flaschen