Reputation: 563
I will try to re explain the situation: I have a paragraph there are 72 words, and they have a toggleClass and these words are highlighted for the user and have a cursor. When any word is clicked I want to check the check mark according to that. So there is 72 check marks each has one.
//adding to 72 paragraph words a toggle class
$(".question_text span").click(function() {
$( this ).toggleClass( "green" );
});
//gives id to every 72 words in the paragrapgh
$('.question_text span').each(function(idx) {
$(this).attr('id', 'a' + idx);
});
// checkmarks have id #Q15v2_1 to #Q15v2_72
So i want when the first word of the highlighted ones clicked to check check marik #Q15v2_1 when the second one is clicked #Q15v2_2 and so on, but when the word is uncliked the check-mark becomes unchecked
Upvotes: 3
Views: 154
Reputation: 17337
I'll take a different approach than others. Render the [i]
with the correct values.
<label for="Q15v2_[i]">text</label>
<input type="checkbox" id="Q15v2_[i]" name="Q15v2_[i]">
That is what label are for, no need for jquery
Upvotes: 0
Reputation: 1896
You can loop thru all elements the add a toggle like this:
$(.question_text span).each(function(){
$(this).click(function(e){
if($(e.target).is(':checked')) {
$(this).prop('checked', false);
} else if($(e.target).is(':checked')) {
$(this).prop('checked', true);
}
})
})
This is only a example, but I think it is the right way to go.
Upvotes: 2
Reputation: 3928
You can do this:
$('.question_text span').each(function(idx) {
$(this).attr('id', 'a' + idx);
});
$(document).on('click', '[id*="Q15v2_"]', function() {
$(this).prop('checked', !$(this).prop("checked"));
});
For the explanation:
I use event delegation: $(document).on('click', '[id*="Q15v2_"]'
in case of you add dynamically your element. The selector [id*="Q15v2_"]
select all element whose id
contains Q15v2_
And this line $(this).prop('checked', !$(this).prop("checked"));
toggle the property checked
of the element you just clicked
Upvotes: 0