javascript - 选项之间的数据传输到相同的值和值
问题描述
有两种不同的选择元素。这些具有相同的价值和文本。还有一个单选按钮。如果选择了具有相同 id 的按钮,我想将第一个选项的值传递给第二个。我为此编写了一个 jQuery 代码。但是,它不是传输,而是创建一个新文本。我希望在第二个中选择相同的值。虽然我搜索了解决问题的示例,但我不知道具体如何搜索。因此,我无法得出结论。
第一个选项
<select id='country-first'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
第二种选择
<select id='country-second'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
单选按钮
Same country: <input type="radio" id="same" value="same">
Different country: <input type="radio" id="different" value="diffent">
jQuery 代码
jQuery(document).on('change', '#same', function() {
if(this.checked) {
jQuery('#country-first').find(":selected").text(jQuery('#country-second').find(":selected").text());
}
});
解决方案
考虑以下示例。
jQuery(function($) {
$(document).on('change', '#same', function() {
if ($(this).is(":checked")) {
$("#country-first option[value='" + $("#country-second").val() + "']").prop("selected", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='country-first'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
<select id='country-second'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
Same country: <input type="radio" id="same" name="fav_language" value="HTML"> Different country: <input type="radio" id="different" name="fav_language" value="CSS">
您的脚本会更改文本,但不会调整选择的选项。使用正确的选择器,您可以重新分配选择的选项。
推荐阅读
- php - WooCommerce 订阅 3.0 | 手动运行计划的操作不起作用
- python-3.x - VS code下添加与vim的键绑定
- ruby-on-rails - Rails 视图中的查询 - 重复查询的最有效方法是什么?
- pyspark-dataframes - 按 pyspark 中空值的列聚合
- c++ - Quickselect algorithm for singly linked list C++
- python - 在python中循环未结束时重复一个函数
- sql - SQL - 从多个值字段中选择
- sum - NetLogo:如何用 NetLogo 计算无穷级数(或部分和)?
- neo4j - 过滤 Ne04j 中选定节点中的键值对列表
- mysql - 无法进行 sql 查询以获取一周前的数据