Ciprian Ciprian - 15 days ago 5
jQuery Question

Get selected values from all dropdowns except one that is triggering event

I want to check if there are any other selected values which match the current selection. So when

.payment-method
changes I get the value and check the other
.payment-method
s for their values. I want to exclude the drop down which triggered the change.
.not(this)
is not working.

$(document).on('change', '.payment-method', function() {
var thisVal = $(this).val();
console.log("this value" + thisVal);

$(".payment-method option:selected").not(this).each(function () {
console.log($(this).val());
});
});

Answer

The issue is because you're using not() against the option elements with this, which references a select, hence it's always false. To fix this, call not() on a selector containing the .payment-method elements and then use find() to get the selected options, like this:

$(document).on('change', '.payment-method', function() {
  $('.payment-method').not(this).find('option:selected').each(function() {
    console.log($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select class="payment-method">
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="fizz">Fizz</option>
  <option value="buzz">Buzz</option>
</select>
<select class="payment-method">
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="fizz">Fizz</option>
  <option value="buzz">Buzz</option>
</select>
<select class="payment-method">
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="fizz">Fizz</option>
  <option value="buzz">Buzz</option>
</select>

Comments