2010-04-04 4 views
1

드롭 다운 상자를 통해 사용자 선택에 따라 다른 옵션을 표시하는 검색 상자에서 작업하고 있습니다. 기본적으로 페이지를 다시로드하지 않고 다른 div를 전환하기 위해 정말 깨끗하고 가벼운 메소드가 필요합니다. 나는 JS에 익숙하지 않지만 JS를 사용하여 디스플레이 속성을 설정하는 몇 가지 간단한 방법이 있어야한다는 것을 충분히 알고있다. 어떤 도움이라도 정말로 감사 할 것입니다.JS 드롭 다운 기준 사용자 입력

+0

당신이 jQuery를 사용하고 있습니까? – SLaks

+0

그래,하지만 나는 아코디언처럼 화려하게 사용하는 것을 피하고 싶다. – Thomas

답변

1

jQuery를 사용하지 않으면 다음과 같이 할 수 있습니다. 진짜 기본 DOM 물건,하지만 어쨌든 ...
그것은 죽음에 댓글을 달았지만, 일반적으로 당신은 그것을 표시/숨기기 당신의 요소가있는 컨테이너 ID를주고 다음 숨기기 - 모든 - 그럼 - 쇼 -one-ofselect 요소 onchange에서 수행됩니다. 표시 할 요소를 검색하는 방법은 basename + suffix (접미어는 해당 요소에 대한 select 옵션의 값입니다)입니다. 여기

:

<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> 
2

여기 jQuery를 사용하고 있으므로 jQuery를 사용한 기본 예제가 있습니다.

저는 몇 분 안에 그것을 던져 버렸기 때문에 완전히 빗나가게하는 것은 아닙니다. 올바른 방향으로 가도록하는 것입니다. 바닐라 HTML 양식 선택 요소를 기반으로 div 스타일을 변경하는 방법을 보여줍니다. jQuery UI를 사용하면 선택 요소를 더 멋지게 볼 수 있지만 꼭 필요한 것은 아닙니다.

<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> 
관련 문제