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") {
$("#cf-query").show("slow");
$("#cf-booking").hide("slow")
} else if ($(this).val() == "I would like to book") {
$("#cf-booking").show("slow")
$("#cf-query").hide("slow")
} else {
$(".cf-section").hide("slow");
}
});
});
<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>
</select>
<div class="cf-section" id="cf-query" style="display: none;">
<h2>Query</h2>
<p>First Name:</p>
<p>Surname*:</p>
<p>Email Address*:</p>
<p>Telephone number*:</p>
</div>
<div class="cf-section" id="cf-booking" style="display: none;">
<h2>Booking</h2>
<p>First Name:</p>
<p>Telephone number*:</p>
</div>
1 Answer 1
Change the option values to the div ids
<option value="cf-query">I have a query</option> ...
Hide all elements with class
cf-section
.Finally reference the value and show it, no need for the multiple if statements.
$("select").change(function() { $(".cf-section").hide(); id = "#" + $(this).val(); $(id).show("slow"); }
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\$R Champniss– R Champniss2016年06月01日 20:38:55 +00:00Commented Jun 1, 2016 at 20:38
-
\$\begingroup\$ jsfiddle.net/skxygmeg \$\endgroup\$R Champniss– R Champniss2016年06月01日 20:42:00 +00:00Commented Jun 1, 2016 at 20:42
-
\$\begingroup\$ Now this has been edited, it works. \$\endgroup\$R Champniss– R Champniss2016年06月02日 18:33:51 +00:00Commented Jun 2, 2016 at 18:33