There are two different select elements. These have equal value and text. There is also a radio button. If the button with the same id is selected, I want to pass the value of the first option to the second. I wrote a jQuery code for this. However, instead of transferring, it creates a new text. I want the same value to be selected in the second one. Although I searched for examples to solve the problem, I did not know exactly how to search. Therefore, I could not come to a conclusion.
First option
<select id='country-first'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
Second option
<select id='country-second'>
<option value='A01'>A</option>
<option value='A02'>B</option>
</select>
Radio Button
Same country: <input type="radio" id="same" value="same">
Different country: <input type="radio" id="different" value="diffent">
jQuery Code
jQuery(document).on('change', '#same', function() {
if(this.checked) {
jQuery('#country-first').find(":selected").text(jQuery('#country-second').find(":selected").text());
}
});
CodePudding user response:
Consider the following example.
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">
Your script changes the text but does not adjust which option is selected. Using the proper Selector, you can then re-assign which Option is selected.