patrick hollweck patrick hollweck - 2 months ago 11
Javascript Question

jquery getting input of multible 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) {
console.log($(this).children("option:selected").prop("value"));
var valueTWO = $("option:selected").prop("value");
});

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select name="" id="ONE">
<option title="A">A</option>
<option title="B">B</option>
</select>
<!-- End td 1 -->
</td>
<td>
<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>
</select>
<!-- End td 2 -->
</td>
<td>




Answer

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:

$(this).children("option:selected").prop("value")

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() );
}