當用戶進行選擇時,我想將表單 Select-Option 的文本部分(而不是值)傳遞給同一表單中的隱藏文本輸入欄位。
我已經探索了一些我在研究中發現的 java 和 PHP “示例”,但它們似乎都不適合我。
我已經發布了表格的原始示例,看看是否有人可以帶我去水。任何幫助將不勝感激。
HMTL
<html>
<head>
</head>
<body>
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
</body>
</html>
uj5u.com熱心網友回復:
它不像獲取所選選項的值那么容易,可以簡單地檢索selectElement.value,但它一點也不難。
selectElement.options將為您提供選擇元素內所有選項的陣列。您會發現所選選項的索引為selectElement.selectedIndex。
話雖如此,您可以像這樣訪問選定的選項:selectElement.options[selectElement.selectedIndex].
最后,您可以獲得這樣的text屬性:selectElement.options[selectElement.selectedIndex].text
這是代碼:
// THIS CONSTANT REPRESENTS THE <select> ELEMENT
const theSelect = document.getElementById('fruitSelector')
// THIS LINE BINDS THE input EVENT TO THE ABOVE select ELEMENT
// IT WILL BE EXECUTED EVERYTIME THE USER SELECTS AN OPTION
theSelect.addEventListener('input', function() {
// THIS IS HOW YOU GET THE SELECTED OPTION'S TEXT
let selectedOptText = theSelect.options[theSelect.selectedIndex].text
// FINALLY, THIS COPIES THE ABOVE TEXT TO THE INPUT ELEMENT:
document.querySelector('.hiddenField').value = selectedOptText;
})
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
uj5u.com熱心網友回復:
好吧,如果你想傳遞文本部分,你應該添加名稱作為值太喜歡
---
code
---
<option value="Grapes">Grapes</option>
<option value="Strawberries">Strawberries</option>
---
code
---
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484104.html
標籤:javascript php 形式
上一篇:不同大小的圓的碰撞
下一篇:如何添加段落文本作為選擇選項?
