检查并整理我的JQuery函数

时间:2016-05-31 21:00:54

标签: jquery show-hide dropdown contact-form-7

我是JQuery的新手但是已经设法让它以我想要的方式运行。问题是,它有点复杂,如果我添加更多选项,很容易失控。

我正在尝试根据用户下拉列表选项显示和隐藏div。我到目前为止已经成为一名JSFiddle,但我认为它可以通过一些精简来实现。



$(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>
&#13;
&#13;
&#13;

有人能给我任何指示吗?我愿意学习! 顺便说一下,我使用CF7来构建表单。

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

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!

    $(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>

感谢您的帮助!