option & jQuery .click() won't work together
this works great in FF but not in IE, Chrome or Safari.
$('#countryDropDown option').click(function() {
var countryID = $(this).val();
dostu开发者_如何学运维ff();
});
// countryDropDown = id of select
So, as you can see I want to attach a click event to each option.
I alos tried
var allOpts = $('#countryDropDown option'),
l = allOpts.length,
i = 0;
for (i = 0; i < l; i += 1) {
$(allOpts[i]).click(function() {
var countryID = $(this).val();
doStuff();
});
}
It still does not want to work in any other browser but FF. What am I doing wrong? Thanks
The question is if you really need to do it this way. I bet you don't need access to the option
element, so you also could use .change()
:
var countryID;
$('#countryDropDown').change(function() {
countryID = $(this).val();
dostuff();
});
Update:
According to the documentation, .val()
should work, but if it does not for whatever reason, do this:
var countryID;
$('#countryDropDown').change(function() {
countryID = $('option:selected', this).val();
dostuff();
});
Update2:
I don't know if it is relevant (I think it should work nevertheless) but could it be that your option
elements don't have a value
attribute, likes so:
<option>Foo</option>
If so you should try .text()
instead of .val()
.
$('option:selected', this).text();
meow we have the same problem...
this is the solution:
if you want to access id of each option. this will do.
$("#countryDropdown").change(function() {
var countryId = $('option:selected',this).attr('id');
dostuff();
});
val() is used to retrieve the value of a form element. An option is not a form element but a sub-element if you will. Further more your approach will not work if they use the keyboard. You are better off doing it this way.
$("#countryDropdown").change(function() {
var countryId = $(this).val();
dostuff();
});
精彩评论