2012-09-27 22 views
35

可能重複:
Getting the value of the selected option tag in a select box獲取SELECT的價值和文本jQuery的

對於選擇框,我如何才能在jQuery中所選項目的價值和文本?

例如,

<option value="value">text</option> 
+0

什麼您已經嘗試 – Gautam3164

+6

這不應該被標記爲重複。可能的重複問如何獲得價值即使該提問者意味着文本 - 這篇文章正確地問如何獲得一個選擇的文本 - 我拉起了這個問題,並在搜索期間通過另一個 - 所以標記這是重複的即使由此產生的答案是相同的,因爲這些問題不是相同的,所以沒有幫助快速判斷!=有幫助 – user1783229

回答

85
<select id="ddlViewBy"> 
    <option value="value">text</option> 
</select> 

JQuery的

var txt = $("#ddlViewBy option:selected").text(); 
var val = $("#ddlViewBy option:selected").val(); 

JS Fiddle DEMO

+1

選定的值不需要選項:選定的選擇器。 $(#ddlViewBy).val()本身就足夠了 –

8
$('select').val() // Get's the value 

$('select option:selected').val() ; // Get's the value 

$('select').find('option:selected').val() ; // Get's the value 

$('select option:selected').text() // Gets you the text of the selected option 

Check FIDDLE

4

你唯一jQuery標籤:)

HTML的基礎上

<select id="my-select"> 
<option value="1">This is text 1</option> 
<option value="2">This is text 2</option> 
<option value="3">This is text 3</option> 
</select> 

對於文本 -

$(document).ready(function() { 
    $("#my-select").change(function() { 
     alert($('#my-select option:selected').html()); 
    }); 
}); 

對於價值 -

$(document).ready(function() { 
    $("#my-select").change(function() { 
     alert($(this).val()); 
    }); 
}); 
12
$("#yourdropdownid option:selected").text(); // selected option text 
$("#yourdropdownid").val(); // selected option value 
6

你可以這樣做,以獲得當前選擇的值:

$('#myDropdownID').val(); 

&獲得當前選定的文本:

$('#myDropdownID:selected').text();