[英]Fill second dropdown with the same value as the first dropdown
I have a dynamic number of dropdowns. 我有一个动态的下拉列表。 When a value is selected in the first dropdown, the value of the second and so on dropdowns will be the same with the first dropdown. 在第一个下拉菜单中选择一个值时, 第二个下拉菜单的值将与第一个下拉列表相同。 But the user has the option to change the value of the second and so on dropdowns , but not changing the first and other dropdown's value. 但是用户可以选择更改第二个下拉菜单的值, 以此类推 ,但不能更改第一个和其他下拉菜单的值。
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
How can I achieve this using javascript or jquery libraries? 如何使用javascript或jquery库实现此目的?
Use a change
event and then alter the other dropdowns: 使用change
事件,然后更改其他下拉菜单:
$("select[name=dropdown\\[\\]]").change(function() {
var value = this.value;
$("select[name=dropdown\\[\\]]").not(this).val(value);
});
Demo: http://jsfiddle.net/awv14f6r/1/ 演示: http : //jsfiddle.net/awv14f6r/1/
If you want to change them in order (first alters the second, etc) - use next
along with this
如果您想按顺序更改它们(第一个更改第二个,依此类推)- this
与next
一起使用
$(this).next("select").val(value);
You can attach a listener to the first select element: 您可以将侦听器附加到第一个select元素:
var selects = document.querySelectorAll('select[name="dropdown[]"]');
selects[0].addEventListener('change', function () {
for (var i = 0; i < selects.length; i++) {
selects[i].value = selects[0].value;
}
});
When the value of only the first select changes, it updates the values of the other selects. 当只有第一个选择的值更改时,它将更新其他选择的值。 This way does not rely on any 3rd-party libraries. 这种方式不依赖任何第三方库。
Demo: http://jsfiddle.net/cuefb9ag/ 演示: http : //jsfiddle.net/cuefb9ag/
var id = $('#DropDownID1 option:selected').val();
var textValue = $('#DropDownID1 option:selected').text();
$('#DropDownID2').prop('selectedIndex', 0);
$('#DropDownID2').select2('data', {
val: id,
text: textValue
});
$('#DropDownID2 option:selected').val(id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.