Question

I have the following html:

<div class="form-group select optional reservation_reception_location">
 <select class="select optional form-control" id="reservation_reception_location_id" name="reservation[reception_location_id]">
   <option value=""></option>
   <option class="Office" value="1">Oddział Częstochowa</option>
   <option class="Airport" value="2">dasdasd</option>
 </select>
</div>

Now my goal is to know the class of selected element. So when i select the first one i will assign its class to value in my coffescript file. I tried something like this:

$('#reservation_reception_location_id').attr('class')

But this show me main div class only. I would be very grateful if someone can help me.

Was it helpful?

Solution

You can use :selected selector to get the selected option:

$('#reservation_reception_location_id option:selected').attr('class')

If you want to get the selected option when your select has been changed, then use .change() event:

$('#reservation_reception_location_id').change(function() {
    var cls = $(this).find('option:selected').attr('class');
    console.log(cls);    
});

Fiddle Demo

OTHER TIPS

$('#reservation_reception_location_id').change(function(){
  var selectedClass=$(this).find("option:selected").attr("class");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top