Set label text using jQuery

This should be pretty straight forward, however the following code does nothing regarding changing the next label text. I tried using .text, .html, etc., but to no avail. Is there something wrong with this code?

<script type="text/javascript"> $(document).ready(function() { $("input:checkbox").on("change", checkboxChange); function checkboxChange() { $("#"+this.id).next("label").text("TESTTTT"); } }); </script> <td width="15%" align="center"><input type="checkbox" name="task1" id="task1"></td> <td width="25%" align="center"><label for="task1"></label></td> 
+8
javascript jquery html onchange
source share
2 answers

The checkbox is in td , so first you need to get the parent:

 $("input:checkbox").on("change", function() { $(this).parent().next().find("label").text("TESTTTT"); }); 

Alternatively, find the label with for with the same id (possibly more productive than the backtrack):

 $("input:checkbox").on("change", function() { $("label[for='" + $(this).attr('id') + "']").text("TESTTTT"); }); 

Or, to be more concise, simply this.id :

 $("input:checkbox").on("change", function() { $("label[for='" + this.id + "']").text("TESTTTT"); }); 
+15
source share

I would simply request a for attribute instead of a repeated recursive DOM tree.

 $("input:checkbox").on("change", function() { $("label[for='"+this.id+"']").text("TESTTTT"); }); 
+8
source share

All Articles