繁体   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