web.dev wrote:
artev wrote:
if I have a select with more options,
how I can know if is there an option selected;
is necessary a cycle? or is there an inner property?
With a select, there is always one option selected
Not necessarily. The W3C specifications do not state that one option
*must* be selected, only that:
"Zero or more choices may be pre-selected for the user."
HTML 4, section 17.6.1
<URL:
http://www.w3.org/TR/html4/interact/...tml#idx-menu-2 >
It then goes on to state how that pre-selection might occur. Also, the
DOM 2 HTML specification includes:
"selectedIndex of type long
"The ordinal index of the selected option, starting from 0.
The value -1 is returned if no element is selected."
It seems unusual to specifically include a value for no selection if it
was thought that it should never occur (though it is by no means proof
of validity).
therefore you don't
need to know if an option has been selected. However, if you really
meant to ask how to know which option is selected, consider the
following:
The answer is that the selected index property can be use to determine
if an option is selected, but not to determine whether that is a
consequence of the user selecting the option, the browser deciding to
preselect a particular option (usually the first) or the HTML
specifying which option is to be preselected.
It might be possible to determine if no option is selected, but I
expect it isn't reliable. How can a user return to no selection without
resetting the form (if that functionality is provided for them at all)?
The best strategy is to ensure that one option (say the first or
zero-th) is always preselected in the HTML, then you know if the user
has selected some other option using:
if ( selectReference.selectedIndex ){
/* some option other than zero is selected */
}
or if you don't like that, try:
if ( selectReference.selectedIndex 0 ){
/* ... */
}
[...]
--
Rob