Jquery Tree Traversal prev () in TD's

I am trying to check / unlock selectbox jquery in a previous TD. For several hours I tried several combinations with prev (), parent (), closeest (), but still without a result ... Here is an example code:

<table>
 <tr>
 <td><input type="checkbox" class="resultcheck"></td>
 <td><label class="resultchecklabel">Text 1</label></td>
 </tr>

 <tr>
 <td><input type="checkbox" class="resultcheck"></td>
 <td><label class="resultchecklabel">Text 2</label></td>
 </tr>

</table>

<script>
$('.resultchecklabel').live('click', function() {
 if ($(this).prev('td input:checked').val() != null) 
 {
  $(this).prev('td').prev("input").removeAttr("checked");
 }
 else
 {
  $(this).prev('td').prev("input").attr("checked","checked");
 }
});
</script>

Who can help me resolve this issue? Many thanks!

+3
source share
3 answers

@Adam and @peterendidit hit a nail on the head - javascript / jQuery is not needed here.

, , , , this - label, td - , label. , , , , - , ..

var cb = $(this).closest('td')  // containing TD
                .prev('td')     // previous TD
                .find('input'); // input within TD
if (cb.find(':checked').length == 0) { // not checked
    cb.attr('checked','checked');
}
else {
    cb.removeAttr('checked');
}
+9

ID for:

 <td><input type="checkbox" id="resultcheck1"></td>
 <td><label for="resultcheck1">Text 2</label></td>

javascript:]

:

. , ( $()):

Id resultchecklabel resultcheck, td = > td = > resultcheck.

: parent = > previous sibling = > child. jQuery, :

var $dest = $(this).parent('td').prev().children('.resultcheck')

, , .

:

http://jsbin.com/evupu/2

+3

Shortcuts don't need fantastic javascript to connect to input elements. Just enter the ID entry and use the for attribute for the label:

<table>
 <tr>
 <td><input type="checkbox" class="resultcheck" id="resultcheck1"></td>
 <td><label class="resultchecklabel" for="resultcheck1">Text 1</label></td>
 </tr>

 <tr>
 <td><input type="checkbox" class="resultcheck" id="resultcheck2"></td>
 <td><label class="resultchecklabel" for="resultcheck2">Text 2</label></td>
 </tr>

</table>
+2
source

Source: https://habr.com/ru/post/1736573/


All Articles