user2507447
user2507447

Reputation: 21

Change one form select option based on other selection

I am using this code. I am using internal script.I am Able to see the first selection ; but value of second selection is not changing due to first selection. I may be missing some basic thing. Please help. please provide a working example.

<!DOCTYPE html>
<html>
<body>
<script>
$(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>");
        }
    });

});
</script>
<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>
</body>
</html>

Upvotes: 0

Views: 4767

Answers (2)

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

You have not imported jquery that is the problem
Copy and paste the below html code in your html page

<html>

<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(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>");
        }
    });

});
</script>

</head>
<body>

<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>
</body>
</html>

Upvotes: 2

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

check this jsfiddle to see the working example http://jsfiddle.net/YPsqQ/

you need to use

 $("#id").change(function() {

//your code here

});

Source: http://jsfiddle.net/YPsqQ/

Upvotes: 1

Related Questions