选择选项时,Javascript更改输入值 [英] Javascript change input value when select option is selected
问题描述
我是javascript的新手。所以我有一个选择选项和一个输入字段。我想要实现的是当我选择一个特定的选项时输入字段的值会改变。这就是我的尝试:
名字:< input type =textvalue =colors>
< select name =>
< option>选择数据库类型< / option>
< option onclick =myFunction(g)> green< / option>
< option onclick =myFunction(r)> red< / option>
< option onclick =myFunction(o)> orange< / option>
< option onclick =myFunction(b)> black< / option>
< / select>
< script>
函数myFunction(g){
document.getElementById(myText)。value =green;
}
函数myFunction(r){
document.getElementById(myText)。value =red;
}
函数myFunction(o){
document.getElementById(myText)。value =orange;
}
函数myFunction(b){
document.getElementById(myText)。value =black;
}
< / script>
一些事情:
你应该在每个单独的选项上使用 onchange
函数,而不是 onclick
。 / p>
在每个选项上使用值
属性来存储数据,并使用的实例此
分配更改(或 event.target
)
您没有ID在您的文本字段
您错过了 onclick
函数的结束报价
< select name =onchange =myFunction(event)>已选择
<选项已禁用>选择数据库类型< /选项>
< option value =Green> green< / option>
< option value =Red> red< / option>
< option value =Orange> orange< / option>
< option value =Black> black< / option>
< / select>
功能:
function myFunction(e){
document.getElementById(myText)。value = e.target.value
}
并添加ID
< input id = myTexttype =textvalue =colors>
小提琴: https://jsfiddle.net/gasjv4hs/
I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:
First Name: <input type="text" value="colors">
<select name="">
<option>Choose Database Type</option>
<option onclick="myFunction(g)>green</option>
<option onclick="myFunction(r)>red</option>
<option onclick="myFunction(o)>orange</option>
<option onclick="myFunction(b)>black</option>
</select>
<script>
function myFunction(g) {
document.getElementById("myText").value = "green";
}
function myFunction(r) {
document.getElementById("myText").value = "red";
}
function myFunction(o) {
document.getElementById("myText").value = "orange";
}
function myFunction(b) {
document.getElementById("myText").value = "black";
}
</script>
A few things:
You should use the onchange
function, rather than onclick
on each individual option.
Use a value
attribute on each option to store the data, and use an instance of this
to assign the change (or event.target
)
You have no ID on your text field
You're missing the end quote for your onclick
function
<select name="" onchange="myFunction(event)">
<option disabled selected>Choose Database Type</option>
<option value="Green">green</option>
<option value="Red">red</option>
<option value="Orange">orange</option>
<option value="Black">black</option>
</select>
And the function:
function myFunction(e) {
document.getElementById("myText").value = e.target.value
}
And add the ID
<input id="myText" type="text" value="colors">
Fiddle: https://jsfiddle.net/gasjv4hs/
这篇关于选择选项时,Javascript更改输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!