Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery show/hide a div based on select value

I have a select list with values 'all' and 'custom'. On select with value 'custom' a div with class 'resources' should appear, and if the value is 'all' it should be hidden.

Form is:

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges" class="" onclick="craateUserJsObject.ShowPrivileges();">
        <option id="all" value="all">All</option>
        <option id="custom" value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div>

And javascript for this is:

ShowPrivileges: function() {
    var Privileges = jQuery('#privileges');
    var select = this.value;
    Privileges.change(function() {
        if (select === 'custom') {
            $('.resources').show();
        }
    });
}

How should this look in order to work? Sorry, I know this should be simple, but I am new with all this.

like image 380
Dušan Avatar asked Mar 26 '13 19:03

Dušan


1 Answers

You can clean up the HTML by dropping the onClick and removing the IDs from the options.

HTML:

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges">
        <option value="all">All</option>
        <option value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div> 

And your JavaScript could simply do this:

$('#privileges').on('change', function() {
        if($(this).val() === 'all') {
            $('.resources').hide();
        } else {
            $('.resources').show();
        }
 });
like image 146
c0deNinja Avatar answered Sep 19 '22 19:09

c0deNinja