Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I show elements based on what is selected in a drop down using jQuery?

Here is my run-of-the-mill drop down:

<select name="">
  <option value="">--Select One--</option>
  <option value="textarea">Text Area</option>
  <option value="textbox">Text Box</option>
  <option value="checkbox">Check Box</option>
  <option value="dropdown">Drop Down</option>
</select>

What I want to do is show show/hide other elements on the page based on if certain options are selected from the drop down.

So if "Text Area" was selected, then a div with the ID "textarea_fields" would show. If something else was then selected, that would hide and the other element would show for that select option.

I'm using jQuery, so using what that library offers is certainly an option.

like image 806
Shpigford Avatar asked Dec 11 '25 04:12

Shpigford


1 Answers

Assuming each div has the class ".panel"

$("select").change(function(){
  $(".panel").hide().filter("#"+ $(this).val() +"_fields").show();
});

You could expand upon this basis to see if the new selection matches that is currently visible if you like. You can determine which is presently opened like this:

var currPanel = $(".panel:visible").attr("id");
like image 135
Sampson Avatar answered Dec 12 '25 19:12

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!