首页 > 解决方案 > 选项之间的数据传输到相同的值和值

问题描述

有两种不同的选择元素。这些具有相同的价值和文本。还有一个单选按钮。如果选择了具有相同 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());
   
        }
}); 

标签: javascriptjquerywordpress

解决方案


考虑以下示例。

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">

您的脚本会更改文本,但不会调整选择的选项。使用正确的选择器,您可以重新分配选择的选项。


推荐阅读