Reputation: 121
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.
Upvotes: 0
Views: 625
Reputation: 2210
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>
Upvotes: 1
Reputation: 207881
Make your function:
$('#testselect').change(function () {
if ($(this).val() == "Yes") {
$("<div><span>test option</span></div>").insertAfter("#inner");
}
})
.find()
looks at descendant elements, so your $(this).find('#testselect :selected')
won't match anything since this
here is already #testselect
. What you might have been thinking of was $(this).find('option:selected').val()
, but $(this).val()
is shorter and more commonly used. Note that repeatedly changing the select element will repeatedly add more test option divs. So you may be better of having a set deiv and just show/hide it.
Upvotes: 1