Welcome to WebmasterWorld Guest from 54.162.117.84

Forum Moderators: open

Message Too Old, No Replies

Question about option selected="selected" and jquery option:selected.

     
9:11 pm on Jun 4, 2012 (gmt 0)

Full Member

5+ Year Member

joined:June 30, 2008
posts: 318
votes: 0


hi all,

I know that the select tag's option selected="selected" just puts the option text in the select's display field on page load.

I also know that...
$('select').val()
$('select :selected').val()
$('select option:selected').val()

and
$('select :selected').text()
$('select option:selected').text()

are all functionally the same in that they all get the current option value and text respectively.

My question is...
Does the jquery selector ":selected" and "option:selected" component attempt to reference the select tag's selected option selected="selected" if any, or does it merely get the value or text of what's currently displayed in the select field and there is no relation between the tag's option="selected" and jquery "option:selected"?
12:44 am on June 5, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


[w3schools.com...]

$('select :selected') returns the element(s) in question

$('select').val() works (in the case of a single selection) as the select element gets it value from the selected item.
1:54 am on June 5, 2012 (gmt 0)

Full Member

5+ Year Member

joined:June 30, 2008
posts: 318
votes: 0


Yes, When i tested my theory in jsfiddle, it appears that $(':select').val() does appear to always get the option where <option selected="selected">.

However, $('select').val() merely gets the currently displayed option regardless of whats been preselected via <option selected="selected">.

[jsfiddle.net ]
2:56 am on June 5, 2012 (gmt 0)

Full Member

5+ Year Member

joined:June 30, 2008
posts: 318
votes: 0


actually this one: [jsfiddle.net...]
5:55 am on June 5, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


All forms should return the currently selected elements regardless of what was preselected via <option selected="selected">..

see demo here [api.jquery.com...]

$('select option:selected') is clearest syntax as it the option element that is selected.

Note that as in demo multiple elements can be returned.

If you need to know what was preselected use say <option selected="selected">
11:49 am on June 5, 2012 (gmt 0)

Full Member

5+ Year Member

joined:June 30, 2008
posts: 318
votes: 0


thanks for helping me clear that up.