2014-01-28 50 views
1

我都有以下HTML:通過它的類部分字符串選擇一個元素

<div id="divAreaId_1" class="SuppAreaParentDiv"> 
     <input type="hidden" value="3" class="hdnMaxSelection_1" id="hdnMaxSelection_1"> 

     <input type="checkbox" id="SuppItemId_2" class="chkSuppItem"> <br /> 
     <input type="checkbox" id="SuppItemId_3" class="chkSuppItem"> <br /> 
     <input type="checkbox" id="SuppItemId_4" class="chkSuppItem"> <br /> 
     <input type="checkbox" id="SuppItemId_5" class="chkSuppItem"> <br /> 

我試圖得到'輸入:隱藏的價值,當任何複選框被選中!我需要通過做「輸入:隱藏」部分類別名稱:

$(".chkSuppItem").click(function() { 
    var hdnMaxSelection = $(this).prev("[class*='hdnMaxSelection_']").val(); 
    alert(hdnMaxSelection); // I am getting here 'undefined'. 

回答

1

您可以使用siblings()

var hdnMaxSelection = $(this).siblings("[class*='hdnMaxSelection_']").val(); 

當前,您的選擇器僅針對第一個複選框進行更正,因爲隱藏的輸入是第一個複選框的前一個兄弟元素。

隨着siblings(),只要你的隱藏輸入是你的複選框的兄弟姐妹,那麼它會工作。

Fiddle Demo

1

你必須在這方面使用.siblings()。因爲.prev()只會使用提供的約束查找前一個兄弟。

嘗試,

$(".chkSuppItem").click(function() { 
    var hdnMaxSelection = $(this).siblings("[class*='hdnMaxSelection_']").val(); 
    alert(hdnMaxSelection); 
}); 

或者你可以用.prevAll(selector)嘗試,

$(".chkSuppItem").click(function() { 
    var hdnMaxSelection = $(this).prevAll("[class*='hdnMaxSelection_']").first().val(); 
    alert(hdnMaxSelection); 
}); 

DEMO for .prevAall()

相關問題