Home  >  Article  >  Web Front-end  >  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
WBOYOriginal
2016-05-16 16:49:361206browse

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值改变后,初始化的值是不会变的。
Statement:
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