tags:

views:

60

answers:

1

Hi there! I'm trying to add a div when an option is selected from the list. This is my main code:

<div>
<select name="rooms" id="rooms">
    <option value="1" label="room 1" selected="selected">1 room</option>
    <option value="2" label="room 2">2 rooms</option>
    <option value="3" label="room 3">3 rooms</option>
</select>       
</div>
<div id="room[number]">
<label>Room 1</label>
<select name="adults" id="adults">
    <option value="1" label="1" selected="selected">1</option>
    <option value="2" label="2">2</option>
</select>
<select name="kids" id="kids">
    <option value="1" label="1" selected="selected">0</option>
    <option value="2" label="2">1</option>
</select>   
</div>

So if you choose 2 rooms, it'll add a div with a different label and id. Any ideas how to make this work?? Live example at www.cheaprooms.com and see "Rooms" options.

Thanks in advance !

+2  A: 

Consider using the <fieldset> element, and rather than adding new ones, hide/show them to ensure functionality in non-JS browsers:

<select name="rooms" id="rooms">
    <option value="1" label="room 1" selected="selected">1 room</option>
    <option value="2" label="room 2">2 rooms</option>
    <option value="3" label="room 3">3 rooms</option>
</select>
<fieldset id="room1">
    <legend>Room 1</legend>
    <select name="adults" id="adults">
        <option value="1" label="1" selected="selected">1</option>
        <option value="2" label="2">2</option>
    </select>
    <select name="kids" id="kids">
        <option value="1" label="1" selected="selected">0</option>
        <option value="2" label="2">1</option>
    </select>
</fieldset>
<fieldset id="room2">
    <legend>Room 2</legend>
    <select name="adults" id="adults">
        <option value="1" label="1" selected="selected">1</option>
        <option value="2" label="2">2</option>
    </select>
    <select name="kids" id="kids">
        <option value="1" label="1" selected="selected">0</option>
        <option value="2" label="2">1</option>
    </select>
</fieldset>
<fieldset id="room3">
    <legend>Room 3</legend>
    <select name="adults" id="adults">
        <option value="1" label="1" selected="selected">1</option>
        <option value="2" label="2">2</option>
    </select>
    <select name="kids" id="kids">
        <option value="1" label="1" selected="selected">0</option>
        <option value="2" label="2">1</option>
    </select>
</fieldset>

Using this jQuery you can hide the rooms you don't need:

$(document).ready(function(){
    $("#rooms").change(function(){
        $("#room1, #room2, #room3").hide();
        for(i=1;i<=parseInt($(this).val());i++) {
            $("#room"+i).show();
        }
    });
    $("#rooms").change(); // Trigger change to set initial state
});
You
I've edited my answer to account for this.
You