jQuery,选择框中所选项目的类

时间:2014-04-28 08:48:19

标签: javascript jquery coffeescript

我有以下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>

现在我的目标是了解所选元素的类。因此,当我选择第一个时,我会将其类分配给我的coffescript文件中的值。我试过这样的事情:

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

但这只是主要的div类。 如果有人可以帮助我,我将非常感激。

2 个答案:

答案 0 :(得分:4)

您可以使用 :selected 选择器来获取所选的选项:

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

如果您想在更改select后获取所选内容,请使用 .change() 事件:

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

<强> Fiddle Demo

答案 1 :(得分:3)

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