Spinbad
Spinbad

Reputation: 158

Finding the selected option of one dropdown among many with same class

the html is

<select class='pay-type' style='width:100%'>
  <option>Credit Card</option>
  <option>Cash</option>
  <option>Credit Note</option>
  option>Gift Voucher</option>
  <option>Cheque</option>
</select>

i reproduce this select by inserting the same html onto new div's. i have a module written which triggers when selection changes in the dropdown. How do i get the selected value of the exact dropdown in the onclick function? the following code doesnt seem to work.

$('.pay-type').change(function(){
  console.log($(this).filter('option :selected'));
}); 

Upvotes: 1

Views: 68

Answers (1)

Abhilash
Abhilash

Reputation: 1610

You are missing a .text()

$('.pay-type').change(function(){
    console.log($(this).filter('option :selected').text()); // to show the text
    console.log($(this).val()); // to show the value
}); 

Note: There are a few things off in your code.

  1. The options do not have a value. Though not strictly essential, it is good practice to have them. If you want to store values in a database, you will now have to store using the text method only.
  2. If you keep your first option as Select a payment method, the user can also select the Credit card option to show in the selected div. Now to do the same thing, the user will have to select something else first and then go back and select that option to see it

Upvotes: 2

Related Questions