Search code examples
htmljqueryhtml-selectselected

Using jQuery to add DOM elements based on option:selected choice


I want to insert elements into the DOM after a named div based on the choice in a drop down option list.

Here is my code to test this.

<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script type="text/javascript" src="../jsstuff/jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
    <script>
     $(funtion(){('#testselect').change(function(){
    var selid = $(this).find('#testselect :selected').val();
    if (selid == "Yes"){
        $("<div><span>test option</span></div>").insertAfter("#inner");
    }
}
)
)
   
</script>
<title>Untitled 2</title>

</head>

<body>
<div id="outer">
    <div id="inner">
        <select id="testselect" name="testselect">
            <option value="" selected="selected"></option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>
    </div>    
 </div>

</body>
</html>

It is not working.


Solution

  • Looks like there are a few mistakes in the code you posted. There are a few simple errors like spelling and a missing $ inside the event handler. Also the way you're getting the value of the dropdown can be simplified. Here's an example.

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
        <script>
        $(function(){
            $('#testselect').change(function() {
                var selid = $(this).val();
                if (selid == "Yes"){
                    $("<div><span>test option</span></div>").insertAfter($("#inner"));
                }
            });
        });
    
    </script>
    <title>Untitled 2</title>
    
    </head>
    
    <body>
    <div id="outer">
        <div id="inner">
            <select id="testselect" name="testselect">
                <option value="" selected="selected"></option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
        </div>    
     </div>
    
    </body>
    </html>