开发者

Getting attr of an option in jQuery

I have a form like this:

<select name="category" id="cat">
<option value="cat1" id="hello">Category1</option>
<option value="cat2" id="hello2">Category2</option>
</select>

if i use $('#cat').val() with change function in #cat id , it displays values(cat1 or cat2).

i want to learn how can i开发者_如何转开发 get id or Category1(or Category2) ?


$('#cat option:selected').attr('id');

the selector :selected will return the selected option in a select element, or an array in case of multiple="multiple"


$('select').change(function() {
    alert($('option:selected',this).attr('id')); 
});

Fiddle: http://jsfiddle.net/each/kqb9S/


Instead of .val(), use .attr().

$('#cat').on('change', function() {
  alert( $(this).children('option:selected').attr('id') )
}) 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="category" id="cat">
  <option value="cat1" id="hello">Category1</option>
  <option value="cat2" id="hello2">Category2</option>
</select>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜