3

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

2
  • 2
    Can you provide the code you wrote please ? Commented Jan 11, 2017 at 12:22
  • sounds like you should be using a label which does it with no JavaScript needed. Commented Jan 11, 2017 at 15:00

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

1 Comment

I do not have control over HTML

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.