patrick hollweck patrick hollweck - 1 year ago 98
Javascript Question

jQuery getting input of multiple select element gives me output of wrong element

I'm having trouble with getting the input of an < select > tag.

I figured out this jQuery snippet but something is wrong... If you run the snippet you can see that it is always just outputting the value of the first < select > element and not correctly outputting the option of the other < select > elements...

// Try the second element.

$("#ONE").on('change', function(eve) {
var valueTWO = $("option:selected").prop("value");

$("#TWO").on('change', function(eve) {
var valueONE = $("option:selected").prop("value");

<script src=""></script>
<select name="" id="ONE">
<option title="A">A</option>
<option title="B">B</option>
<!-- End td 1 -->
<select class="" id='TWO' name="">
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
<!-- End td 2 -->

Answer Source

Your $("option:selected") selector is not being limited to only the changed dropdown - it's saying "Select all selected options on the entire page", and because there are multiple, it returns the first.

Try doing this instead:


By doing $(this).children, you've narrowed down your selector to look only at options within the changed dropdown.

That being said, you can do a .val() on a dropdown/select to get the value, instead of having to traverse through selected options:

$('#mySelect').change(function() {
    console.log( $(this).val() );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download