Home >Web Front-end >JS Tutorial >js code to get the value of the current select element_form effects

js code to get the value of the current select element_form effects

WBOY
WBOYOriginal
2016-05-16 18:29:531149browse

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 select.selectedIndex.
3. The selected option element can be obtained through select.options[select.selectedIndex].
4. option element, the value attribute value of the option element can be obtained through option.value, which is value3; it can be obtained through option.text The text within the option element, i.e. text3.
5. If the option element does not define the value attribute, option.value cannot be obtained in IE, but Safari, Opera, and FireFox can still obtain it through option.value, and the value is the same as option.text.
6. You can use option.attributes.value && option.attributes.value.specified to determine whether the option element defines the value attribute.

Therefore, the script to obtain the current select element value is as follows:

Copy the code The code is as follows:

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

In the past, due to compatibility issues, everyone used select.options[select.sekectedIndex].value to get the value, but now you can use select.value

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

Event triggering can also be used