Welcome to WebmasterWorld Guest from 54.166.114.43

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)

5+ Year Member



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 Jun 5, 2012 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



[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 Jun 5, 2012 (gmt 0)

5+ Year Member



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 Jun 5, 2012 (gmt 0)

5+ Year Member



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

WebmasterWorld Senior Member 5+ Year Member



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 Jun 5, 2012 (gmt 0)

5+ Year Member



thanks for helping me clear that up.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month