jQuery on a SELECT not working in IE but works in all other browsers
I'm trying to get a drop down menu to set/change a class on a div depending on the value of the option selected. This works fine in all my main browsers except IE7 and 8. Any ideas what I'm doing wrong?
<html>
<head>
开发者_如何转开发<script type="text/javascript" src="/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function() {
$('#outerwrapper').find('select').change(function () {
var str1 = "";
$("select option:selected").each(function () {
str1 = $(this).attr('value');
});
$("#swatch").removeClass().addClass('mycssclass_' + str1);
})
.change();
});
</script>
</head>
<body>
<div id="outerwrapper">
<form action="/" method="POST" name="test">
Choose:
<select id="in_clr" name="clr"><!-- By choosing an option from this list... -->
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div id="swatch"><!-- I want jQuery to add a CSS class of mycssclass_1 (or 2 or 3) to this DIV -->
</div>
</form>
</div>
</body>
</html>
I have tried replacing .change with .live("change", but that doesn't seem to make any difference.
Change your selector from: $('#outerwrapper').find('select')
to: $('#in_clr')
From my experience, DOM Traversal over form elements can be odd in IE. You don't need the extra chaining anyway.
I believe you can condense your coding down quite a bit to just:
$(document).ready(function(){
$('#outerwrapper select').change(function() {
$("#swatch").removeClass().addClass('mycssclass_' + $(this).val());
});
});
Jsfiddle.
The .ready
only runs once the element is available (you can change to using .live
if you are using ajax-y stuff.
Note that this will bind the change event to all select elements -- use #in_clr
if you only want to target that particular select.
As for why IE was failing, it was probably your :selected
call or the .attr()
as IE is very picky about attributes and properties.
精彩评论