Search code examples
jqueryshow-hidedropdowncontact-form-7

Check and tidy up my JQuery function


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 users dropdown selection. I've made a JSFiddle with where I am so far, but I think it could do with some streamlining.

$(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.2/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>

Could anyone give me any pointers? I'm willing to learn! BTW, I'm using CF7 to build the form.

JSFiddle: http://jsfiddle.net/rchampniss/mdy7acwn/


Solution

  • I've found the solution!

        $(function() {
            $('#cf-dd-nature').change(function(){
                $('.cf-section').hide();
                $('#' + $(this).val()).show();
            });
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><h2>What is the nature of your enquiry*:</h2>
    
    <select id="cf-dd-nature">
        <option value="">--</option>
        <option value="cf-query">I have a query</option>
        <option value="cf-booking">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>

    Thanks for your help!