簡體   English   中英

如何使用javascript將選擇中的值發送到html中的輸入文本?

[英]How to send a value from a select to an input text in html using javascript?

我正在嘗試根據諸如的下拉列表中的選擇將值發送到。 我想獲取possiblePhone.id的值並將其發送給。

<script>
function copyTextValue() {
    var text1 = document.getElementById("source").value;
    document.getElementById("destination").value = text1;

}
</script>


<div>
<select th:field="${possiblePhones}">
    <option value="0">select phone</option>
    <option id="source" onselect="copyTextValue()"
            th:each="possiblePhone : ${possiblePhones}"
            th:value="${possiblePhone.id}"
            th:text="${possiblePhone.model}"></option>
</select>
</div>

<td><input type="text" id="destination"> </td>

例如,如果選擇“三星”,則應將“ 1”發送到輸入字段,依此類推。 實際上,我沒有任何輸出。

<select id="source" onchange="copyTextValue()">
    <option value="0">select phone</option>
    <option value="1">samsung</option>
    <option value="2">something</option>
</select>

id="source"屬性應位於<select>元素中,還將onselect更改為onchange並將其也移至<select>元素。

Codepen: https ://codepen.io/anon/pen/WVxLpz

您可以通過將偵聽器設置為select元素,然后查詢所選的選項值來實現。

我用兩個品牌做了一個最小的例子:

 <script> function copyTextValue() { var e = document.getElementById("select"); var val = e.options[e.selectedIndex].value; document.getElementById("destination").value = val; } </script> <div> <select onchange="copyTextValue()" id="select"> <option value="0">select phone</option> <option value="1">Brand 1</option> <option value="2">Brand 2</option> </select> </div> <td><input type="text" id="destination"> </td> 

您必須在此處觀察的一件簡單的事情是,必須在選擇下拉列表時捕獲事件,並將當前的下拉引用傳遞給您的方法。

<script>
function copyTextValue(selectedOption) {
if(selectedOption.selectedIndex <= 0){
document.getElementById("destination").value = '';
return;
}

 var selectedOptionValue = selectedOption.value;
 document.getElementById("destination").value = selectedOptionValue;
}
</script>
<div>
<select onChange="copyTextValue(this);">
    <option value="0">select phone</option>
    <option value="1">select first phone</option>
    <option value="2">select second phone</option>
    <option value="3">select third phone</option>
    <option value="4">select fourth phone</option>

</select>
</div>

<td><input type="text" id="destination"> </td>

在這里,您還試圖避免在選擇第一個元素時將任何值傳遞給文本框。 @kryptur的答案也是正確的,但這比較簡單。

您正在使用Thymeleaf。 對於這些,您可以創建一個表單以將數據發送到服務器。

按照此鏈接獲取有關您的確切問題的文檔。

https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#creating-a-form

像Thymeleaf這樣的框架通常將狀態存儲在服務器上,這意味着您首先要更新服務器-然后您的UI將被更新。

返回的值是選擇字段的值,您需要做的就是獲取所選選項的文本,即

function copyTextValue() {
var selectNode = document.getElementById("source");
enter code here
  document.getElementById("destination").value = 
  selectNode .options[selectNode .selectedIndex].textContent;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM