我想将此功能添加到表单中。当从下拉菜单中选择一个选项时,我希望它输入上面的文本字段和相应的信息。例如:
<form name="form1" action="formhandler">
<input type="text" name="typecar">
<select name="BMWCars">
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>
</form>
如何在不需要连接到以获取字符串的情况下完成此操作?
最佳答案
如果使HTML符合您的需要,那么代码会更整洁。
http://jsfiddle.net/TgM2W/3/
<form name="form1" id="form1" action="formhandler">
<input type="text" name="typecar" id="typecar">
<select name="BMWCars" id="BMWCars">
<option value="">Select one...</option>
<option value="5-series">Sedan</option>
<option value="6-series">Convertibles</option>
<option value="X5">Truck</option>
<option value="3-series">Coupe</option>
<option value="5-series GT">Hatchback</option>
</select>
</form>
JavaScript(不带jQuery):
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = function() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value = opts[opts.selectedIndex].value;
};
};
或者使用jQuery:
$(document).ready(function() {
$('#BMWCars').change(function() {
var opts = $(this)[0].options;
$('#typecar').val(opts[opts.selectedIndex].value);
});
});
但是,如果无法更改HTML,则只需使用一个对象来存储值并引用:
objBMW = {
"Sedan":"5-series",
"Convertible":"6-series",
"Truck":"X5",
"Coupe":"3-series",
"Hatchback":"5-series GT"
};
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = changer;
};
function changer() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value =objBMW[opts[opts.selectedIndex].value];
};
关于javascript - 如何根据在下拉菜单中选择的内容在字段中获得不同的信息?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7585873/