我有2个选择框,我想将它们的值添加到基于更改选择框的选择框中。我写了下面的代码。但它只适用于一个。 我怎样才能做到这一点 ? 这是我的代码:
// initialize the counters outside of the loop
var counters = [];
$.each(data, function (i, object) {
if (!object.last_activity_at) return true;
counters[object] =counters[object] ? counters[object] + 1 : 1;
});
// keep next loop out side because you will get multiple line of same date with different number
// now returning the same kind of dates
var keys = Object.keys(counters);
$(keys).each(function(index,key){
$("body").append("<p> "+key+":" + counters[key] + "</p>");
})
&#13;
var selectBox = document.getElementById('mySelect');
var selectBox2 = document.getElementById('mySelect2');
selectBox.addEventListener('change', handleChange);
selectBox2.addEventListener('change', handleChange);
function handleChange()
{
var selectedValue = this.options[this.selectedIndex].value;
document.getElementById('myInput').value = selectedValue;
document.getElementById('myInput2').value = selectedValue;
}
&#13;
答案 0 :(得分:2)
var selectBox = document.getElementById('mySelect');
var selectBox2 = document.getElementById('mySelect2');
selectBox.addEventListener('change', handleChange);
selectBox2.addEventListener('change', handleChange);
function handleChange(event)
{
if (event.target.id == "mySelect") {
document.getElementById('myInput').value = selectBox.value;
} else {
document.getElementById('myInput2').value = selectBox2.value;
}
}
<select id="mySelect">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
<select id="mySelect2">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
<input type="text" id="myInput" />
<input type="text" id="myInput2" />
答案 1 :(得分:2)
由于您使用jquery标记了您的问题,我可能还提供基于jquery的答案:
$('[id^=mySelect]').change(function(){
$('#'+this.id.replace('Select','Input')).val($(this).val())
});
这个简短的片段应该可以随心所欲。我的第一个选择器[id^=mySelect]
将选择以“mySelect”开头的所有 ID,如果您希望将此代码段的范围扩展到进一步的选择和输入,这将非常有用。如果这不是您想要的,您可以使用更明确的版本#mySelect,#mySelect1
替换它。