Reputation: 171419
How should I understand
$("select option:selected")
in the following code ?
(taken from here)
$("select").change(function() {
...
$("select option:selected").each(function () {
...
});
...
})
Is it all selected options in all selects in the document ?
Is it somehow related to the current select, $(this) ?
Upvotes: 8
Views: 3242
Reputation: 106392
$("select option:selected")
will select an element who is a option
that has the selected
attribute set, which is a child of a select
element. It will find all selected options on the page. It is not related to the clicked element $(this)
- if you wanted it to be, use .find()
like so: $(this).find('option:selected')
.
.each()
then iterates over each selected option on the page doing something with each element.
Upvotes: 0
Reputation: 382826
Yes, the code is correct !
Is it all selected options in all selects in the document ?
Yes, it does.
Is it somehow related to the current select, $(this) ?
Yes, $(this)
is related to current element.
The following code iterates over all the options of all select boxes that are selected:
$("select option:selected").each(function () {
...
});
Therefore, you could do:
$("select").change(function() {
...
$(this).find("option:selected").each(function () {
...
});
...
})
Upvotes: 0
Reputation: 187100
$("select")
will find all select elements in the document.
and inside the change event you can give
$(this).find("option:selected")
to get all the option selected for the current select element.
Your statement will fetch all selected options for all select elements inside the document.
Upvotes: 0
Reputation: 5935
It's selected options from whole document.
You can use find
to select only from $(this)
Upvotes: 1
Reputation: 72668
Yes, it will refer to all selected options in all selects. If you just want to look at the current select, you can do something like this:
$("select").change(function() {
...
$(this).find("option:selected").each(function () {
...
});
...
})
Upvotes: 14