Patrioticcow
Patrioticcow

Reputation: 27038

jQuery, how to check for a selected option from a form select?

I have this form select:

<select name="select_date" id="select_date">
    <optgroup label="Select Date">
        <option value="0" selected="selected">Custom Date</option>
    </optgroup>
    <optgroup label="Or Custom Date">
        <option value="1"> Current Month</option>
        <option value="2"> Last Month</option>
        <option value="3"> Last 3 Months</option>
        <option value="4"> Last 6 Months</option>
        <option value="5"> Last Ever</option>
    </optgroup>
</select>

<div id="test">hide me</div>

How can I check for a selected option so that: if option 3 selected then hide the div with id test?

Upvotes: 1

Views: 3835

Answers (3)

vzwick
vzwick

Reputation: 11044

$('#select_date').change(function(){
    if ($('option:selected', this).val() == 3) $('div#test').hide();
});

Edit: Bonus: working fiddle

Upvotes: 1

Sahil Muthoo
Sahil Muthoo

Reputation: 12509

Example

$('#select_date').change(function() {
    $('#test').show();
    if($(this).val() === '3') {
        $('#test').hide();
    }
});

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

$("#test").toggle($("#select_date").val() != 3);

Wrapped in an event handler for the change event:

$("#select_date").bind("change", function () {
    $("#test").toggle(this.value != 3);
}).change();

Example: http://jsfiddle.net/Qde8d/

Notes:

  • Use the version of toggle that takes a showOrHide parameter to show #test when the selected option is not 3, and hide it when it is 3.
  • Access the current value of the select element using this.value inside the event handler or .val() if you're working with a jQuery object.

Upvotes: 4

Related Questions