jQuery - 选择选项时添加div

时间:2010-08-01 22:05:26

标签: jquery

我正在尝试从列表中选择一个选项时添加div。这是我的主要代码:

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

因此,如果你选择2个房间,它会添加一个带有不同标签和id的div。任何想法如何使这项工作?在www.cheaprooms.com上观看实例并查看“会议室”选项。

提前致谢!

1 个答案:

答案 0 :(得分:2)

考虑使用<fieldset>元素,而不是添加新元素,隐藏/显示它们以确保非JS浏览器中的功能:

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

使用此jQuery,您可以隐藏不需要的房间:

$(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
});