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
JavaScript
x
5
1
<select id='country-first'>
2
<option value='A01'>A</option>
3
<option value='A02'>B</option>
4
</select>
5
Second option
JavaScript
1
5
1
<select id='country-second'>
2
<option value='A01'>A</option>
3
<option value='A02'>B</option>
4
</select>
5
Radio Button
JavaScript
1
3
1
Same country: <input type="radio" id="same" value="same">
2
Different country: <input type="radio" id="different" value="diffent">
3
jQuery Code
JavaScript
1
7
1
jQuery(document).on('change', '#same', function() {
2
if(this.checked) {
3
jQuery('#country-first').find(":selected").text(jQuery('#country-second').find(":selected").text());
4
5
}
6
});
7
Advertisement
Answer
Consider the following example.
JavaScript
1
7
1
jQuery(function($) {
2
$(document).on('change', '#same', function() {
3
if ($(this).is(":checked")) {
4
$("#country-first option[value='" + $("#country-second").val() + "']").prop("selected", true);
5
}
6
});
7
});
JavaScript
1
10
10
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<select id='country-first'>
3
<option value='A01'>A</option>
4
<option value='A02'>B</option>
5
</select>
6
<select id='country-second'>
7
<option value='A01'>A</option>
8
<option value='A02'>B</option>
9
</select>
10
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.