2017-05-26 43 views
1

我有2个形式自动填充文本形式值后选择一个选项的形式

<select> 
    <option>Rose</option> 
    <option>Violet</option> 
</select> 

<input type="text" value="Autofill here" /> 

如果用户选择玫瑰,文本形式的值将是“红色”自动。

如果用户选择紫罗兰,文本表单值将自动为“蓝色”。

你有一个简单的例子吗?

回答

2

使用jQuery,添加更改事件来选择,将选定的值设置为文本输入。注意:您需要添加蓝红先在HTML选择选项:使用JQuery

$('#myselect').on('change', function(){ 
 
    $('#myinput').val($(this).val()); 
 
}) 
 

 
// init 
 
$('#myselect').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="myselect"> 
 
    <option value="Red">Rose</option> 
 
    <option value="Blue">Violet</option> 
 
</select> 
 

 
<input id="myinput" type="text" value="Autofill here" />

+0

我认为OP希望在文本框中进行打印,而不是改变的颜色值文本框。 – JanR

+1

@JanR哦,是的,谢谢 –

+0

@JanR对! :D –

2

基本思想:

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<select class="colorPicker"> 
    <option value="Red">Rose</option> 
    <option value="Blue">Violet</option> 
</select> 

的Javascript:

$(document).ready(function(){ 
     //when the select changes: 
    $('.colorPicker').on("change", function(){ 
     //set the value of the input to the value of the select. 
      $('.colorDisplay').val($(this).val()); 
    }); 
}); 

原则上,我们绑定一个函数来改变select的事件。使用一个类来标识输入字段和选择。当用户选择一个选项时,输入会自动更新为所选选项的值。

小提琴here

+0

不错的一个,+1了 –

0

使用香草的JavaScript

var e = document.getElementById("selectFlower"); 
 
e.addEventListener("change", function() { 
 

 
    var val = e.options[e.selectedIndex].text; 
 
    document.getElementById("inp").value = val; 
 

 
}); 
 

 
// To show preselected value 
 

 
var val = e.options[e.selectedIndex].text; 
 
document.getElementById("inp").value = val;
<select id="selectFlower"> 
 
    <option>Rose</option> 
 
    <option>Violet</option> 
 
</select> 
 

 
<input type="text" id="inp" value="Autofill here" />

0
<select id="sel"> 
    <option value="Rose">Rose</option> 
    <option value="Violet">Violet</option> 
</select> 

<input id="test" type="text" value="Autofill here" /> 

JS代码是

var selection = document.getElementById("sel"); 
document.getElementById("test").value(selection.options[ selection.selectedIndex ].value) 

从这个让JS代码的功能,并将其与onchange属性添加到input

1

您可以尝试

var e = document.getElementById("selectFlower"); 
e.addEventListener("change", function(){ 
    $('#inp').css('color', $('#selectFlower').val()); 
}); 

<select id="selectFlower"> 
     <option value="red">Rose</option> 
     <option value="blue">Violet</option> 
</select> 

<input type="text" id="inp" value="Autofill here" /> 
+0

它的很好的答案,但我需要的是文本形式的自动填充值。 –

+0

哈哈,谢谢兄弟,我想你需要颜色,对不起。 –