2012-07-03 31 views
0

我試圖將輸入的值設置爲所點擊的列表項的值。當他們都在同一格內,存在其中類=容器jquery如何在同一個div內設置輸入值

jQuery的

$('li').click(function(){ 

    /* Somehow set the value of the input that is within the same div 
    with class equal container to the data-personguid on this li. */ 

}); 

HTML

<div class="container"> 
    <div> 
     <ul> 
      <li data-personguid="3" /> 
      </li> 
     </ul> 
    </div> 
    <input type="hidden" class="personguid" id="thirdinput" /> 
</div> 

<div class="container"> 
    <div> 
     <ul> 
      <li data-personguid="4" /> 
      </li> 
     </ul> 
    </div> 
    <input type="hidden" class="personguid" id="fourthinput /> 
</div> 

因此,如果與L1數據-personguid = 3被點擊我想輸入與id = thirdinput有它的值設置爲3.

同樣,如果li與data-personguid = 4被點擊,我會想輸入與id = fourthinput有它的值設置爲4.

所以我想我會試圖做的是找到類class personguid的輸入是在class = container的同一個div中作爲點擊的 列表項並設置它的值。

目前不確定如何做到這一點。

jquery需要是通用的,因此每個容器塊都使用相同的代碼。

回答

2
$('li').on('click', function(){ 
    $(this).closest('.container').find('.personguid').val($(this).data('personguid')); 
}); 
+1

+1這是正確的答案。 – iambriansreed

0

這將是更容易,如果你只是追加號碼與您的ID,這樣你就不必硬編碼每一個在

$('li').click(function(){ 
    var x = $(this).data('personguid'); 
    $('#input'+ x).val(x); 
}); 

所以,你的投入將是ID =輸入1,ID =輸入2,ID = input3等