Home > Web Front-end > JS Tutorial > js obtains the selected Option by default and is not the currently selected value_javascript skills

js obtains the selected Option by default and is not the currently selected value_javascript skills

WBOY
Release: 2016-05-16 16:49:36
Original
1228 people have browsed it

js函数方法:

复制代码 代码如下:

<script> <br>function getDefaultSelectedOption(selectId, valIfNull) { <br>var dom, selectId = selectId.replace(/^#/, ''), opts; <br>try { <br>opts = document.getElementById(selectId).getElementsByTagName('option'); <br>for (var i in opts) { <br>if (opts[i].defaultSelected) { <br>dom = opts[i]; <br>break; <br>} <br>} <br>} catch (e) { <br>} <br>return dom||valIfNull; <br>} <br></script>

Demo:
复制代码 代码如下:




<script> <br>function getDefaultSelectedOption(selectId, valIfNull) { <br>var dom, selectId = selectId.replace(/^#/, ''), opts; <br>try { <br>opts = document.getElementById(selectId).getElementsByTagName('option'); <br>for (var i in opts) { <br>if (opts[i].defaultSelected) { <br>dom = opts[i]; <br>break; <br>} <br>} <br>} catch (e) { <br>} <br>return dom||valIfNull; <br>} <br></script>
<script> <br>document.getElementById('btn').onclick = function () { <br>alert((getDefaultSelectedOption('sel1', {})).value); <br>}; <br></script>


不知道还有没有更方便快捷的方法,曾尝试通过jQuery获取$('#sel option[defaultSelected]'),可一直返回空。

各位园友,我要的是select控件初始化的值,非select当前选中的值,初始化的值不随select值改变,大家可以做一下Demo,当select值改变后,初始化的值是不会变的。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template