KSK
KSK

Reputation: 205

To get the selected values using Jquery

I need to get the selected value from a table using jquery am dont get any values, kindly help me out

Here is my code:

$(this).parents("tr:first").find("td:nth-child(1).option:selected").text();

<td>
     <select id="grams">
         <option value=""></option>
         <option value="100">100g</option>
         <option value="250">250g</option>
         <option value="500">500g</option>
     </select>
</td>

Thanks for looking into this.

Upvotes: 1

Views: 115

Answers (3)

Jai
Jai

Reputation: 74738

Try with these as you have specified an id to the element you can get the value straight from that:

$('#grams').val(); // gets the current option value
$('#grams option:selected').val(); // gives you the selected option value

and if you want it to get through binding the change event:

// with a selector's context way

$('#grams').on('change', function(e){
   console.log($('option:selected', this).val());
});

// with find() method of jQuery

$('#grams').on('change', function(e){
   console.log($(this).find('option:selected').val());
});

Upvotes: 0

intellidiot
intellidiot

Reputation: 11228

This should work:

$("#grams").val();

Here is a quick fiddle for this.

Upvotes: 1

Rahul
Rahul

Reputation: 5636

To Read Select Option Value use

$('#grams').val();

To Set Select Option Value use

$('#grams').val('newValue');

To Read Selected Text use

$('#grams>option:selected').text();

Hope it works.

Upvotes: 2

Related Questions