SoFunction
Updated on 2025-02-28

js code to get the current select element value

1. If all option elements under the select element do not specify the selected attribute, the first one will be selected by default.
2. You can get the index of the selected option element through
3. The selected option element can be obtained through [].
4. The option element <option selected="selected" value="value3">text3</option> can obtain the value attribute value of the option element, that is, value3; the text inside the option element, that is, text3 can be obtained.
5. If the option element does not define the value attribute, it cannot be obtained in IE, but Safari, Opera, and FireFox can still be obtained through , with the same value as .
6. You can use && to determine whether the option element defines the value attribute.

Therefore, the script that obtains the current select element value is as follows:
Copy the codeThe code is as follows:

var getSelectValue = funtion(select) {
var idx = ,
option,
value;
if (idx > -1) {
option = [idx];
value = ;
return (value && ) ? : );
}
return null;
}

In the past, due to compatibility issues, everyone used [].value to get the value, but now it's OK

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

Event triggering can also be used
<select onchange="alert(getSelectValue(this))">
It is better to bind events.