Skip to content Skip to sidebar Skip to footer

Show/hide Certain Fields Based On Select List

I am attempting to use JavaScript and/or jQuery to hide certain html elements based on which item is selected in a drop down menu. The page looks like this: [Drop down menu] [text

Solution 1:

Firstly, there is no onselect, you probably wanted onchange. Secondly, you're using jQuery, so use it. Thirdly, change the markup to somehow include what you want, data attributes are great.

<selectstyle="width: 120px;"name="farm_in"id="farm_in"><option></option><optionvalue="option1.com"data-show="[1,2,3,4]">option1.com</option><optionvalue="option2.com"data-show="[2,3,4]">option2.com</option><optionvalue="option3.com"data-show="[2,3,4,5]">option3.com</option></select><br><inputstyle="width: 120px;"type="text"name="one"id="el1"value="one"><br><inputstyle="width: 120px;"type="text"name="two"id="el2"value="two"><br><inputstyle="width: 120px;"type="text"name="three"id="el3"value="three"><br><inputstyle="width: 120px;"type="text"name="four"id="el4"value="four"><br><inputstyle="width: 120px;"type="text"name="five"id="el5"value="five">

Then all you have to do is

$('#farm_in').change(function() {
    $('input').hide();
    $('#el' + $('option:selected', this).data('show').join(', #el')).show();
});

FIDDLE

Solution 2:

For starters, this doesn't identify an element in your DOM:

$('#five')

You don't have an element with an id of "five". Instead, you're looking for this:

$('input[name="five"]')

(Or, conversely, you could give an id attribute to your elements.)

Aside from that, I'm not aware of any onselect event for an option element. Why not respond to the change event of the select instead (and de-couple from the markup a bit while you're at it)?:

$('select').on('change', function () {
    if ($(this).val() === 'option3.com') {
        $('input[name="five"]').hide();
    } else {
        $('input[name="five"]').show();
    }
});

Solution 3:

Looking at you fiddle you are missing the ID attributes for your text fields.

<input style="width: 120px;"type="text" name="five" value="five">

Should be:

Also I would recommend splitting you JS from your HTML.

Post a Comment for "Show/hide Certain Fields Based On Select List"