开发者

JS Display Content based on Dropdown User input

开发者 https://www.devze.com 2022-12-25 08:48 出处:网络
I am working on a search box that displays different options based on a users selection via dropdown box. Basically I need a really clean, light-weight method for switching out different divs without

I am working on a search box that displays different options based on a users selection via dropdown box. Basically I need a really clean, light-weight method for switching out different divs without reloading the page. Im new to JS, b开发者_StackOverflow社区ut I know enough that there should be some really simple way of setting the display property using JS - Im just not totally sure how to go about it. Any help would be really appreciated, thanks.


Since you're using jQuery here is a basic example using jQuery.

I threw it together in a few minutes, so it's not intended to be fully fleshed out, it's just to get you in the right direction. It shows you how to change the style of divs based on a vanilla HTML form select element. If you use jQuery UI you can get a nicer looking select element, but it's not neccesary.

<html lang="en">
<head>
    <title>Dynamic Form Example</title>
    <!-- this is the class you will use to style the hidden divs
        or even the visible ones. I'm using display: none, but
        you can style them however you want: visibility: hidden,
        zero width, etc etc -->
    <style>
        .hidden { display: none }
    </style>
    </link>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        var myApp = {
            init: function init(){
                $("#food_select").change(function(evnt){
                    myApp.setComment(this.value);
                });

                //Set default value
                document.my_form.food_select.selectedIndex = 0;

                //Show appropriate comment for default value
                myApp.setComment(document.my_form.food_select[0].value);
            },

            setComment: function setComment(food){
                // This is jus an example, you will prob
                // need more complicated logic, maybe a switch etc
                if((food === "pizza") || (food === "burrito")){

                    // here we toggle the class that styles the elements
                    //     the second argument is whether the class should
                    //      be added or removed
                    $("#yum").toggleClass("hidden", false);
                    $("#yuck").toggleClass("hidden", true); 
                };
                if((food === "haggis") || (food === "sardines")){

                    $("#yum").toggleClass("hidden", true);
                    $("#yuck").toggleClass("hidden", false); 
                };
            }
        };
        $("document").ready( function () { myApp.init() } );
    </script>
</head>
<body>
<div id="yuck">YUCK!</div>
<div id="yum">mmmm yummy.</div>
<div id="form_div">
<form name="my_form">
<select name="food" id="food_select">
<option value="pizza">Pizza</option>
<option value="burrito">Burrito</option>
<option value="sardines">Sardines</option>
<option value="haggis">Haggis</option>
</select>
<button id="submit_food_button" value="submit">Submit</button> 
</form>
</div>
</body>
</html>


Not using jQuery, here's a little something that can do it. Real basic DOM stuff, but anyway...
It is commented to death, but in general you give it a container id (in which your elements to show/hide are), and then some hide-all-then-show-one-of-them is done in the select element's onchange. The way to retrieve element to show is basename+suffix (and the suffix is the value of the select's option for a corresponding element).

Here:

<body>

<select id="mySelect" onchange="npup.doSelect(this);">
    <option value="">Npup says 'select'</option>
    <!-- the option values are suffixes for the elements to show -->
    <option value="0">zero</option>
    <option value="1">one</option>
    <option value="2">two</option>
</select>
<!-- container for any elements that are to be in the game -->
<div id="mySpecialElements">
    <!--  these have ids that end with and index  for easy retrieval in "findeElement" function  below-->
    <div id="npup0" class="hidden">div 0</div>
    <div id="npup1" class="hidden">div 1</div>
    <div id="npup2" class="hidden">div 2</div>
</div>

<script type="text/javascript">

window.npup = (function (containerId, baseId) {
    // save the container of your special element
    var elementsContainer = document.getElementById(containerId);
    function doSelect(select) {
        // get value of select
        var value = select.value;
        // find element based on the value of the select
        var selected = findElement(value);
        if (!selected) {return;} // didn't find the element, bail
        // do hiding/showing of elements
        hideAll(elementsContainer);
        showElement(selected);
    }
    // retrieve some element based on the value submitted
    function findElement(value) {
        return document.getElementById(baseId+value);
    }
    // hide all element nodes within some parent element
    function hideAll(parent) {
        var children = parent.childNodes, child;
        // loop all the parent's children
        for (var idx=0, len = children.length; idx<len; ++idx) {
            child = children.item(idx);
            // if element node (not comment- or textnode)
            if (child.nodeType===1) {
                // hide it
                child.style.display = 'none';
            }
        }
    }
    // display a certain element
    function showElement(element) {
        element.style.display = '';
    }
    // hide all on page load (might want some extra logic here)
    hideAll(elementsContainer);

    // export api to use from select element's onchange or so
    return {
        doSelect: doSelect
    };
})('mySpecialElements', 'npup'); // give the routine a container id of your special elements, and the base id of those elements
</script>
</body>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号