2012-08-22 3 views
1
<select id="testSelection"> 
      <option> test1 </option> 
      <option> test2 </option> 
      <option> test3 </option> 
      <option> test4 </option> <--- selected this one from the pull down menu 
      <option> test5 </option> 
      <option> test6 </option> 
    </select> 

      $("#testSelection").change(function() 
      { 
        alert($(this).text()); 
      }); 

경고 메시지에는 모든 선택 사항이 표시되지만 test4 텍스트에만 표시 될 것으로 예상됩니다.jquery를 사용하여 풀다운 메뉴의 선택된 옵션 값을 얻는 방법은 무엇입니까?

+1

가능한 중복 [엄선하여 JQuery와의 선택된 옵션의 텍스트를 얻는 방법?] (HTTP : // 유래 그러나, 당신이 그렇게처럼, 당신의 option 요소 value 속성을 추가 할 필요가 있습니다 .com/questions/1391019/how-to-the-get-the-selected-of-a-select-using-jquery) – j08691

답변

5
<select id="testSelection"> 
    <option value="1">test1</option> 
    <option value="2">test2</option> 
    ..... 
</select> 

정말 당신이 원하는에 따라 달라집니다

$("#testSelection").on('change', function() { 
    // if you just want the text/html inside the select (ie: test1, test2, etc) 
    alert($(this).find('option:selected').text()); 

    // or you want the actual value of the option <option value="THISHERE"> 
    alert($(this).val()); 
});​ 

jsFiddle DEMO

+1

거짓입니다. 두 메소드 모두에서 값 = ""을 반환합니다. 선택한 항목. 이것은 당신이 내가 보여주고 자하는 것입니다 : http://jsfiddle.net/XCSgG/4/. 첫 번째 val()은 선택한 값의 텍스트를 반환하는 text() 여야합니다. 두 번째 val()은 select 메뉴의 값을 반환합니다. –

+0

고맙습니다. 그것들을 거꾸로 쓰십시오. (틀린 : .val()은 선택된 것을위한 것입니다) –

1

당신은 val() 기능이 아닌 text() 기능을 사용해야합니다.

$("#testSelection").change(function() 
{ 
    alert($(this).val()); 
});​ 
0

$(this).text() 수익률이 경우 요소 내의 모든 텍스트는 select 요소입니다. 그래서 "test1 test2 ..."이됩니다. 선택한 옵션의 값 속성을 원하는 경우에

$(this).find(':selected').text() 

는 다음 @mcpDESIGNS '대답은 작동합니다

선택한 옵션의 텍스트를 원하는 가정.

<option value="test4">test4</option> 
관련 문제