I'm working on learning Javascript and jQuery, and have come across a problem in the example code below that I wrote which I can't seem to figure out the cause of. I was attempting to write a script that would cause the second select dropdown to mirror the selected option in the first dropdown.
I'm curious to know why my current code seems to be targeting only every other select option. I'm newly learning Javascript/jQuery so I'm sorry if this is an obvious answer, but I would really appreciate if someone could explain to me why this code is targeting only half of my select options rather than all of them, in addition to how to fix it, so that I can learn from this mistake.
<style>
#sweets {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<select id="sweets" >
<option value="Chocolate">Chocolate</option>
<option value="Candy">Candy</option>
<option value="Taffy">Taffy</option>
<option value="Caramel">Caramel</option>
<option value="Fudge">Fudge</option>
<option value="Cookie">Cookie</option>
</select>
<select id="target">
<option value="Chocolate">Chocolate</option>
<option value="Candy">Candy</option>
<option value="Taffy">Taffy</option>
<option value="Caramel">Caramel</option>
<option value="Fudge">Fudge</option>
<option value="Cookie">Cookie</option>
</select>
<script>
$( "#sweets" )
.change(function () {
var str = "";
$( "option:selected" ).each(function() {
str += $( this ).val();
});
$( "#target" ).val( str );
})
.change();
</script>
Also, here is a JSFiddle of the same code. https://jsfiddle.net/2xnmr0pa/1/
The problem is in the following code:
$( "option:selected" ) // selected options from ANY list on the page
This selects all selected options from BOTH lists, not just the first one.
Therefore, each time you select a value on your first list, you also take the currently selected value from the other list, append them both and then try to set that as the new value of the second list.
The fix is simple, just limit your selection of selected options to the first list by changing the above code to:
$( "#sweets option:selected" ); // selected options in the #sweets list
Or you could use the fact that jQuery switches the context (the value of this) in attached functions to the element that the function was attached to and just find its selected option:
$(this).find('option:selected')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With