Reputation: 18103
<optgroup label="Food">
How can i do so when you press this link
<a class='clickMe' id='Food'>Show </a>
It should select the first <option>
in the optgroup
, that has the optgroup label "Food" (taken from the 'id' attribute in the link)
$('.clickMe').live('click', function(){
var label = $(this).attr('id');
// How can i select the first option from the optgroup label here?
});
Maybe if it helps, the select has name="product[][category]"
Upvotes: 2
Views: 2772
Reputation: 76003
//bind a click event handler to any elements that have the `.clickMe` class
$('.clickMe').live('click', function(){
//change the value of the select input to the first option in the optgroup that has a label that is equal to the id of the link clicked
$('select').val($('optgroup[label="' + this.id + '"]').children('option:first').val());
});
Here is a jsfiddle of this solution: http://jsfiddle.net/jasper/LqmJG/
Here's a quick break-down of the magic above:
$('optgroup[label="' + this.id + '"]')
: selects the option group with the label that matches the id of the link clicked..children('option:first').val()
: selects the first option (which is a child of the already selected optgroup tag) and gets its value.<select>
element.Upvotes: 2
Reputation: 24236
Try -
var opt = $("select > optgroup[label=Food] > option:first");
Upvotes: 0