422
422

Reputation: 5770

dynamic dropdown list ( select boxes )

Here is the issue.

I have a select dropdown list.

   <select name="listingtype" id="speedD" style="width:210px;">
      <option>For Sale</option>
      <option>For Rent</option>
   </select>

And another select drop down list where the prices appear , which on page load it is empty..

So if user clicks For Sale: then the other select drop down list, loads price list like so:

   <select name="valueA" id="speedF" style="width:200px;">
     <option value="Any" selected="selected">Any</option>
     <option value="50000">$50,000</option>
     <option value="100000">$100,000</option>
     <option value="150000">$150,000</option>
     <option value="200000">$200,000</option>
     <option value="250000">$250,000</option>

And if they choose For Rent. Select drop down is propagated like so:

<select name="valueA" id="speedF" style="width:200px;">
    <option value="Any" selected="selected">Any</option>
    <option value="100">$100</option>
    <option value="150">$150</option>
    <option value="200">$200</option>
    <option value="250">$250</option>
    <option value="300">$300</option>
</select>

I need this code to be client side, no need for server side. And just wanted to know what the cleanest method for doing this is.

Cheers.

Upvotes: 0

Views: 2891

Answers (2)

kstev
kstev

Reputation: 740

First of all I recommend setting the value attribute in your option elements. Example:

<option value="sale">For sale</option>
<option value="rent">For rent</option>

If you have not already heard of or seen the JavaScript library known as jQuery I strongly recommend checking it out! It can be very helpful when creating a dynamic site like this using minimal JavaScript.

I would do something like the following:

<html>
...
<body>
<div id="fillme"></div>
<script type="text/javascript">
    if (document.yourformname.listingtype.value == "sale") {
        //it is for sale
        $('#fillme').html('<select name="valueA" id="speedF" style="width:200px;"><option value="Any" selected="selected">Any</option><option value="50000">$50,000</option><option value="100000">$100,000</option><option value="150000">$150,000</option><option value="200000">$200,000</option><option value="250000">$250,000</option></select>');
    } else {
        //fill it with the other elements
    }
</script>
</body>
</html>

Now of course you could load it more dynamically with JSON or XML but that is up to you. I really recommend checking out the library: http://jQuery.com

Upvotes: 2

DavidJCobb
DavidJCobb

Reputation: 1131

Use JavaScript to fill the empty select with options when the user selects an option (either onchange or onselect, forget which) in the For Sale/For Rent select.

EDIT: More specifically, have that second box be empty when the page loads. Store the options in arrays. Use a loop to create new OPTION elements based on each array item.

Upvotes: 1

Related Questions