My HTML is generated by the website and I can’t change this:
<div>
<span class="wrapper">
<input type="checkbox" value="" id="nr1" name="X">
<label for="X">
<span class="Y">
<span class="title">Text nr 1</span>
</span>
</label>
</span>
</div>
I’m trying to use jQuery to change the text in <span class="title">
when checkbox id=nr1
is checked. (I have many of these checkboxes with different IDs and different texts and I want to change the text always to the same outcome when the box is checked.
I have made this jQuery code:
$('#submit').on("click", function(){
$("input:checkbox(:checked)").each(function() {
$(this).find( $(".title").text("Checked"));
});
});
But it doesn’t seem to select the correct object as I can’t get the output back correctly. it seems to do "nothing" (I can’t enable errors in the system I’m working on so I can’t see why it would not work).
Can someone point me in the right direction?
2
Answers
You need to include
.next()
, as.find()
searches descendants, and the span isn’t a descendant of the checkbox, but it is a descendant of the next element in the DOM.Also, the proper selector syntax for your example is
$("input:checkbox:checked")
, not$("input:checkbox(:checked)")
Note that the label’s
for
attribute should match theID
of another element, not thename
.At a glance I see two issues:
$(this).find( $(".title").text("Checked"));
.title
withininput:checkbox(:checked)
because it’s not a child of that element.The first issue is just more familiarity with jQuery syntax and functions. The second requires an understanding of DOM traversal. Rather than looking within the checkbox element, traverse up to a common parent (e.g.
span.wrapper
) then then find the target within that element.For example: