Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

jquery - how to change a selections options based on another select option selected?

here is my html.

<select id="type">
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>

<select id="size">
<option value="">-- select one -- </option>
</select>

here is the jquery i tried but was unsuccessful.

$(document).ready(function() {

if( $("#type").val("item1"))
{
  $("#size").html("<option value='test'>test</option><option value="test2">test2</option>);
}
elseif( $("#type").val("item2"))
{
   $("#size").html("<option value='anothertest1'>anothertest1</option>");
}

});

basically what i'm trying to do is if an option is selected in #type then the size select is populated with options associated to it. how can i do this?

thanks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example of what you are trying to do => fiddle

$(document).ready(function () {
    $("#type").change(function () {
        var val = $(this).val();
        if (val == "item1") {
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
        } else if (val == "item2") {
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");
        } else if (val == "item3") {
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
        } else if (val == "item0") {
            $("#size").html("<option value=''>--select one--</option>");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="type">
    <option value="item0">--Select an Item--</option>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<select id="size">
    <option value="">-- select one -- </option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...