I'm new to jQuery but have managed to get it working the way I want. The problem is, it's a bit convoluted and could easily get out of hand if I add more options.

I am trying to show and hide divs based on a user's dropdown selection. I've made a JSFiddle with where I am so far, but I think it could do with some streamlining.

I'd like to be able to add five more dropdown options, with five more divs to show or hide. Will I need to hide each of them individually, or is there a way to say "if the div id is not the value selected, then hide it"?

I'm using CF7 to build the form.

$(function() {
    $("select").change(function() {

        if ($(this).val() == "I have a query") {
        } else if ($(this).val() == "I would like to book") {

        } else {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<h2>What is the nature of your enquiry*:</h2>

<select id="cf-dd-nature">
    <option value="">--</option>
    <option value="I have a query">I have a query</option>
    <option value="I would like to book">I would like to Book</option>

<div class="cf-section" id="cf-query" style="display: none;">
    <p>First Name:</p>
    <p>Email Address*:</p>
    <p>Telephone number*:</p>

<div class="cf-section" id="cf-booking" style="display: none;">
    <p>First Name:</p>
    <p>Telephone number*:</p>


1 Answer 1

  1. Change the option values to the div ids

    <option value="cf-query">I have a query</option>
  2. Hide all elements with class cf-section.

  3. Finally reference the value and show it, no need for the multiple if statements.

    $("select").change(function() {
      id = "#" + $(this).val();

Now you can add as many as you want and your jQuery function code never changes.

  • \$\begingroup\$ I feel like an idiot, but I still can't get this to work. Could you send a fiddle? \$\endgroup\$ Commented Jun 1, 2016 at 20:38
  • \$\begingroup\$ jsfiddle.net/skxygmeg \$\endgroup\$ Commented Jun 1, 2016 at 20:42
  • \$\begingroup\$ Now this has been edited, it works. \$\endgroup\$ Commented Jun 2, 2016 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.