2014-02-17 32 views
1

我試圖在選中複選框後獲取最接近的Textfield值。這只是一個簡單的HTML示例。在我的項目中,我已經動態地添加了帶有多個複選框的列表。我總是需要最接近的Textfield的值 - 就像一個表明hte複選框和文本字段屬於一起的引用。謝謝!如何在點擊複選框後獲得最接近的Textfield值 - jQuery

HTML:

<input type='checkbox' class='oberpunkte' name='checkbox' value='typo 3'/> 
<input type='text' name='text' value='typo3txt'/> 
<input type='button' name='test' id='123' value='Alert'/> 

JQuery的:

$("#123").click(function(){ 
$('input:checkbox[class=oberpunkte]:checked').each(function() { 
    alert($(this).closest('input[type=text]').attr('value')); 
    }); 
}); 

小提琴: http://jsfiddle.net/pEb7D/1/

+1

'$(本)。接下來的值( 'input [type = text]')。attr('value')'[** Demo **](http://jsfiddle.net/pEb7D/3/) –

+0

在這種情況下,您想使用兄弟姐妹http:///api.jquery.com/siblings/ –

+0

Dhaval Marthak的解決方案爲我工作。 @RobSchmuecker有更喜歡兄弟姐妹而不是next()嗎? – Preprocezzor

回答

0

我會建議使用父()和find(),比讓他們之間的連接,所以如果你將來的html改變,你不需要改變javascript。

$("#123").click(function() { 
    $(this).parent().find('selectorToInput').DO_STUFF; 
} 
2

將是「更好」,如果你換你的HTML在<div class="box">但像你所擁有的,你可以使用上一個或下一個取決於其中點擊情況:

http://jsfiddle.net/pEb7D/4/

$(".oberpunkte").change(function(){ 
     alert($(this).next('input').val()) 
}); 

$('#123').on('click',function(){ 
    alert($(this).prev('input').val()); 
}); 

作爲父母的div.box更新 在我看來這是一個更好的解決方案。原因不要緊,你點擊就可以從$(this)檢查哪裏是最接近框,然後得到我們正在尋找...

http://jsfiddle.net/pEb7D/7/

<script type="text/javascript"> 
    $("#123, .oberpunkte").on('click', function(){ 
      alert($(this).closest('.box').children('.needToFind').val()) 
    }); 
</script> 

<div class="box"> 
    <input type='checkbox' class='oberpunkte' name='checkbox' value='typo 3'/> 
    <input class="needToFind" type='text' name='text' value='typo3txt'/> 
    <input type='button' name='test' id='123' value='Alert'/> 
</div> 

<div class="box"> 
    <input type='checkbox' class='oberpunkte' name='checkbox' value='typo 3'/> 
    <input class="needToFind" type='text' name='text' value='123456'/> 
    <input type='button' name='test' id='123' value='Alert'/> 
</div> 

<div class="box"> 
    <input type='checkbox' class='oberpunkte' name='checkbox' value='typo 3'/> 
    <input class="needToFind" type='text' name='text' value='xxxxxx'/> 
    <input type='button' name='test' id='123' value='Alert'/> 
</div> 
+0

@preprocezzor做了答案對您有幫助嗎? – caramba

相關問題