更新時(shí)間:2022-09-09 09:44:26 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1904次
大家在Java在線學(xué)習(xí)技術(shù)文檔中會(huì)學(xué)到很多知識(shí),在本文中,我們將學(xué)習(xí)在 Javascript 中獲取下拉列表中的選定值。我們可以使用 2 種方法獲取值:
1.通過使用 value 屬性
2.通過將 selectedIndex 屬性與 option 屬性一起使用
我們將通過示例了解這兩種方法。
可以使用定義列表的選定元素上的 value 屬性找到選定元素的值。此屬性返回一個(gè)字符串,表示列表中<option>元素的 value 屬性。如果未選擇任何選項(xiàng),則不會(huì)返回任何內(nèi)容。
句法:
選擇元素值
示例:此示例描述了可以為選定元素找到的 value 屬性。
<!DOCTYPE html>
<head>
<title>
How to get selected value in
dropdown list using JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to get selected value in dropdown
list using JavaScript?
</b>
<p> Select one from the given options:
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
<option value="premium">Premium</option>
</select>
</p>
<p> The value of the option selected is:
<span class="output"></span>
</p>
<button onclick="getOption()"> Check option </button>
<script type="text/javascript">
function getOption() {
selectElement = document.querySelector('#select1');
output = selectElement.value;
document.querySelector('.output').textContent = output;
}
</script>
</body>
</html>
輸出:

selectedIndex 屬性返回下拉列表中當(dāng)前選定元素的索引。此索引從 0 開始,如果未選擇任何選項(xiàng),則返回 -1。options 屬性返回<select> 下拉列表中所有選項(xiàng)元素的集合。元素根據(jù)頁面的源代碼進(jìn)行排序。在它之前找到的索引可以和這個(gè)屬性一起使用來獲取被選中的元素??梢允褂?value 屬性找到此選項(xiàng)的值。
句法:
selectElement.options[selectElement.selectedIndex].value
適當(dāng)?shù)膬r(jià)值:
selectedIndex:用于設(shè)置或獲取集合中選中的<option>元素的索引。
length:它是只讀屬性,用于獲取集合中<option>元素的數(shù)量。
返回值:通過指定<select>元素中的所有<option>元素返回 HTMLOptionsCollection 對(duì)象。該元素將在集合中排序
示例:此示例描述了 selectedIndex 屬性和 option 屬性。
<!DOCTYPE html>
<head>
<title>
How to get selected value in
dropdown list using JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to get selected value in
dropdown list using JavaScript?
</b>
<p> Select one from the given options:
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
<option value="premium">Premium</option>
</select>
</p>
<p> The value of the option selected is:
<span class="output"></span>
</p>
<button onclick="getOption()">Check option</button>
<script type="text/javascript">
function getOption() {
selectElement = document.querySelector('#select1');
output = selectElement.options[selectElement.selectedIndex].value;
document.querySelector('.output').textContent = output;
}
</script>
</body>
</html>
輸出:

以上就是關(guān)于“使用JavaScript獲取下拉框的value值”的介紹,大家如果對(duì)此比較感興趣,不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的JavaScript教程,里面還有更豐富的知識(shí)等著大家去學(xué)習(xí),希望對(duì)大家能夠有所幫助。
Java實(shí)驗(yàn)班
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
Java就業(yè)班
有基礎(chǔ) 直達(dá)就業(yè)
Java夜校直播班
業(yè)余時(shí)間 高薪轉(zhuǎn)行
Java在職加薪班
工作1~3年,加薪神器
Java架構(gòu)師班
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)