2011-04-06 53 views
0
 
<label for="radio1"> 
     This Radio Button 1 has a label associated with it.</label> 
    <input type="radio" name="Radio" id="radio1" /> 

上面的代碼有一個標籤和單選按鈕,該標籤與使用for屬性的單選按鈕關聯。使用javascript獲取關聯的單選按鈕標籤文本

如果用戶選擇/檢查相關的單選按鈕,我想獲得標籤文本。

回答

1
$('input#radio1').prev('label[for=radio1]').text(); 
1
$("input:radio").click(function() { 
    // if the label is before the radio button 
    alert($(this).prev("label").text()); 
    // otherwise use 
    alert($("label[for='" + this.id + "']").text()); 
}); 
3

我知道這個問題是個老了,甚至已經有一個公認的答案,但每這裏的迴應使用prev方法。只是想指出的是,一個稍微更強大的技術將使用屬性選擇:

$('input:radio').click(function() { 
    var txt = $('label[for=' + this.id + ']').text(); 
    alert(txt); 
}); 
0

您還可以使用:

$("input:radio").click(function() { 
    var label_description = this.parentElement.outerText; 
    alert(label_description); 
}) 

的js小提琴測試:

Get the label for a radio

相關問題