jQuery如何获取所选索引

时间:2014-04-22 16:23:41

标签: jquery select indexing

我有一些标记:

<select name="serviceID[1]" id="serviceID[1]" class="computeThisService">
<option value="" selected="selected">No Selection</option>
<option value="4">TJ5</option>
<option value="1">TJ2</option>
<option value="5">TJ1</option>
<option value="2">TJ3</option>
</select>

我正在尝试获取所选值,但这不起作用:

  var triggerID = event.target.id; // get the id that triggered the event
  var nStart = triggerID.indexOf('[') + 1;
  var nEnd = triggerID.indexOf(']');
  j = triggerID.substring(nStart, nEnd); // get the index of the id that triggered the event

  var el = $('select option:selected', this);
  alert(el.text());

2 个答案:

答案 0 :(得分:2)

您可以使用selectedIndex

$("#serviceID\\[1\\]")[0].selectedIndex

<强> Fiddle Demo

答案 1 :(得分:1)

对于jQuery,你只需要这个 -

$('select option:selected').text();

所以在你的情况下它可以是

$('#serviceID\\[1\\] option:selected').text();

http://jsfiddle.net/jayblanchard/StMd2/