Frage

I'm trying to get the closest Textfield's Value after checking a checkbox. This is just a simple HTML example. In my project I have dynamically added Lists with multiple checkboxes. I always need the closest Textfield's value - something like a refenrence that shows that hte checkbox and the textfield belongs together. Thanks!

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'));
    });
});

Fiddle: http://jsfiddle.net/pEb7D/1/

War es hilfreich?

Lösung

would be "nicer" if you wrap your html in a <div class="box"> but like what you have it you can use prev or next depending where the click happens:

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

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

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

UPDATE with a div.box as parent In my opinion this is a nicer solution. Cause doesn't matter where you click we can check from $(this)where is the closest box and then get the value we're looking for...

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>

Andere Tipps

I would suggest using parent() and find(), than make a connection between them, so if you future html changes you would not need to change the javascript.

$("#123").click(function() {
    $(this).parent().find('selectorToInput').DO_STUFF;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top