2011-12-12 29 views
12

在我的HTML表單中(如在大多數HTML表單中),標籤與字段共享相同的ID。我試圖返回到標籤標籤的HTML一旦點擊與匹配的ID複選框。jQuery給出輸入ID,獲取標籤文本

<input id="yes1" type="checkbox"> 
<label for="yes1">This is the text it should return.</label> 

而且我的jQuery:

$('input').change(function() { 
    if (this.checked) { 
     var response = $('label#' + $(this).attr('id')).html(); 
    } 
} 

但很可惜,反應出來爲NULL。

+0

你仰視'標籤#yes1',但沒有對象相匹配的選擇。 – jfriend00

回答

30
$('input').change(function() { 
    if (this.checked) { 
     var response = $('label[for="' + this.id + '"]').html(); 
    } 
}); 

無需從屬性得到ID 。

演示:http://jsfiddle.net/wycvy/

-2

你的語法有點wacked,嘗試建立HTML像這樣

<input id="yes1" type="checkbox" /> 
<label for="yes1" id="yes1-label">This is the label</label> 

,然後使用jquery像這樣

$("#yes1").click(function() { 
if ($("#yes1").is(":checked")) { 
    /* it's not really clear what you are trying to do here */ 
    var response = $("#label").attr("id"); 
    $("#yes1-label").text(response); 
} 
}); 
0

這裏是基本的例子,按照您的要求。您需要複選框旁邊標籤的html內容(如果選中)。

使用本

HTML

<div> 
<form > 
<input type="checkbox" id="yes" /><label for="yes">text yes </label> 
<input type="checkbox" id="no" /><label for="no">text no</label> 

</form> 


</div> 

JQUERY

$('input').change(function() { 
     if (this.checked) { 
      var response = $(this).next("label").html(); 
      alert(response); 
     } 
    })