Karthik
Karthik

Reputation: 317

What is the more correct/efficient selector?

$("select").change(function() {

                alert($("select option:selected").val());

            });

OR

$("select").change(function() {

            alert($(this).attr("value"));

            });

I am specifically looking at the selector used in the alert. From my testing the result in the same correct values to be displayed.

Upvotes: 0

Views: 56

Answers (2)

Gumbo
Gumbo

Reputation: 655189

First of all they are not equivalent. The first will give you the value of the selected options of any select element while the second will give you the value only of the one you changed.

So you should absolutely use the second example.

Upvotes: 1

Russ Cam
Russ Cam

Reputation: 125488

They are different. The first will get the value of the first selected <option> in the DOM (in any of the <select> elements).

The second one will work fine, and of course, there are several variations that do the same thing

$("select").change(function() {
            alert($(this).val());
            });

$("select").change(function() {
            alert($('option:selected', this).val());
            });

to name a couple

Upvotes: 3

Related Questions