最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how do I get the text instead of the value - Stack Overflow

programmeradmin2浏览0评论

I have this HTML:

<select class="business_types_select" name="business_type_id">
<option value="0" selected="selected">Select a Business Type</option>
     <option value="54">Bakery</option>
      <option value="55">Tobacco</option>
</select>

and if I select Bakery and then try:

 $(".business_types_select").val()

I get 54, but how do i get the text Bakery? If I try

 $(".business_types_select").text()

I get:

" Select a Business Type Bakery Tobacco "

I have this HTML:

<select class="business_types_select" name="business_type_id">
<option value="0" selected="selected">Select a Business Type</option>
     <option value="54">Bakery</option>
      <option value="55">Tobacco</option>
</select>

and if I select Bakery and then try:

 $(".business_types_select").val()

I get 54, but how do i get the text Bakery? If I try

 $(".business_types_select").text()

I get:

" Select a Business Type Bakery Tobacco "
Share Improve this question edited May 5, 2011 at 18:29 Nic 13.8k7 gold badges42 silver badges43 bronze badges asked May 5, 2011 at 18:12 Matt ElhotibyMatt Elhotiby 44.1k91 gold badges224 silver badges328 bronze badges 1
  • possible duplicate of jquery get selected text from dropdownlist – Naftali Commented May 5, 2011 at 18:19
Add a ment  | 

5 Answers 5

Reset to default 11

Try:

$(".business_types_select :selected").text()

Without this, the .text() is behaving like it should, which is to bring back all of the text from that particular class. Adding :selected to the selector narrows it down to just the one you have selected.

Remember to cache your selectors if you're going to be operating on them often for performance.

You have to reduce the selector to the selection option:

$(".business_types_select").find('option:selected').text();

Like this:

$(".business_types_select > option:selected").text()

(In the short example here I have assumed that there is only one <select class="business_types_select" />. My jsfiddle example is more prehensive.)

$(".business_types_select option:selected").text()

That will return the text of the selected option only

$(".business_types_select").find('option:selected').text();
发布评论

评论列表(0)

  1. 暂无评论