2017-05-26 78 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

哈哈,謝謝兄弟,我想你需要顏色,對不起。 –