[英]How to set text value from `select` drop list into `input` text field?
我是java
初學者,不熟悉javascript
或php
,因此我可以根據自己的需要瀏覽和復制簡單的javascript/php
代碼示例。 這樣我就在stackowerflow中找到了並嘗試實現我的需要:
腳本:
<script type="text/javascript">
function onchange() {
var e = document.getElementById("persId");
var persSelected = e.options[e.selectedIndex].text;
document.getElementById("myInput").value=persSelected;
}
</script>
和身體:
<body>
<div th:replace="fragments/main.html :: top_menu"/>
<div class="w3-container" align="center">
<form action="/add" method="post" class="w3-container w3-card-4 w3-light-grey w3-text-blue w3-margin w3-center" style="width: 50%" >
<h2 class="w3-center">Add the challenger</h2>
<select name="pers" id="persId" onchange="onchange();">
<option th:each="person: ${personList}">
<title id="titleId" th:text="${person.getName()}"/>
</option>
</select>
<div class="w3-row w3-section">
<div class="w3-col" style="width:50px"><i class="w3-xxlarge fa fa-user"></i></div>
<div class="w3-rest">
<input class="w3-input w3-border" id="myInput" name="lastName" type="text" onkeyup="myFunction()" placeholder="Search for last names.." title="Type in a last name">
</div>
</div>
我得到的名單person
進入跌幅榜,但沒有選擇的項目為input
文本字段。
如何正確實現此代碼?
看起來像這樣的行:document.getElementById(“ persId”)。value = persSelected;
應該是:document.getElementById(“ myInput”)。value = persSelected;
我不知道-如何以及為什么在script
塊中使用參數type
。。但是,當我刪除此代碼時: type="text/javascript"
一切正常
您的代碼有問題
讓我解釋。
這段代碼沒有意義:
<option th:each="person: ${personList}">
<title id="titleId" th:text="${person.getName()}"/>
</option>
選項沒有標題。 相反,您應該只在選項內使用文本。 像這樣:
<option th:each="person: ${personList}">
${person.getName()} // this should just turn into text
</option>
因此您最終將獲得:
<option th:each="person: ${personList}">
John Doe
</option>
好吧,現在要做的第一件事就是解決您的其他問題。 :)
這條線本來可以工作。
var persSelected = e.options[e.selectedIndex].text;
但是由於選項中沒有元素,因此我們需要將值獲取到其他位置。
最簡單的方法是獲取select元素的值。
像這樣:
var persSelected = document.getElementById("persId").value;
這是一個工作腳本文件的示例:
腳本:
<script type="text/javascript">
function onchange() {
var persSelected = document.getElementById("persId").value;
document.getElementById("myInput").value = persSelected;
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.