views:

176

answers:

4

How to show/hide a checkbox based on select option value? I want to show a checkbox based on a single value in select option and want to hide it when other values are selected. I am trying for jquery solution.

$('#abcselect').change(function(){$('#unknownlicense').toggle($(this).val() == 'first')});
+4  A: 
$(document).ready(function() {
    $("select").change(function() {
        $("#foo").toggle($(this).val() == "something"));
    }).change(); // in case the first option is selected on page load
});

Try it out: http://jsfiddle.net/JMGMx/3/

Also, see http://api.jquery.com/toggle/ and http://api.jquery.com/slidetoggle/

karim79
somehow not working ..check my updated first post with the code
yogsma
@yogsma - my bad. The `change` handler needs to be triggered once the page has loaded in case the option of interest happens to be the first one in the list. See my edit (and updated demo). Also make sure that 'first' refers to the value as opposed to the text, otherwise you need to use `$(this).text()`. Hope that solves it!
karim79
didn't work either. I am not showing div section as you showed in your example. I am using a row of a table to display
yogsma
@yogsma - Kindly post your markup, so I/we can figure out what's going on.
karim79
@yogsma - just a thought, but that change handler needs to be in a `$(document).ready(...` block, in case you don't have that. Please see my edit.
karim79
@karim79 - I have done the same. But doesn't work.
yogsma
+1  A: 
    $('#YourSelectId').change(function () {
        if($(this).val() == 'TheValueOftheOptionThatHasCheckboxes'){
            $('#IdOfDivContainingTheCheckBoxes').show();
        }
        else{
            $('#IdOfDivContainingTheCheckBoxes').hide();
        }
    });
Patricia
A: 

You could always set that checkbox (or the surrounding div) to the same ID as the value in the select option so that when that value is selected, you just do a:

$('#sameIDasOption').show();
Munzilla
A: 

You can bind to the select option changed using jquery with code similar to the following:

$('.target').change(function() { 
    alert('Handler for .change() called.'); 
 });

You can show and hide with the .show() and .hide() methods.

You can combine these to do something like

$('#SelectId').change(function (){
    if($(this).val() == 'ShowCheckBox'){
         $('DivWithCheckboxes).show()
     }
     else{
         $('DivWithCheckboxes).hide()
     }
});

You can find more information about the functions at:

http://api.jquery.com/change/
http://api.jquery.com/show/
http://api.jquery.com/hide/

sparks