How To Check/Uncheck Corresponding Checkbox

Each word in a p tag is wrapped in a span tag. Clicking a word will trigger .toggleClass('green'). How do I check or uncheck the corresponding checkbox to the clicked word. Each word and checkbox has an id ending in a numeric value.

// adds ids a[i]
$('.question_text span').each(function(idx) {
    $(this).attr('id', 'a' + idx);
});
// adds span class
$(".question_text span").click(function() {
    $( this ).toggleClass( "green" );
});

// checkmark ids only changes the last digit Q15v2_[i], 
$('#Q15v2_[i]').prop('checked', true);

// else false
$('#Q15v2_[i]').prop('checked', false);

1 answer

  • answered 2017-01-11 14:23 PeterKA

    Without the html to clear determine the placement of the input:checkbox elements in relation to the span elements, while adding id attributes to the span elements also add references to the corresponding input:checkbox elements and you should be good to go:

    // adds ids a[i]
    $('.question_text span').each(function(idx) {
            //create a data-attribute that references the corresponding checkbox
        //You may want to prepend # so it is referencing the selector
        $(this).attr('id', 'a' + idx).data('id','#Q15v2_' + idx);
    });
    // adds span class
    $(".question_text span").click(function() {
        $( this ).toggleClass( "green" );
        //check or uncheck the correspinding checkbox
        //this actually returns the selector
        var checkboxid = $(this).data('id');
        //depending on whether .green class is added or removed, check
        //or uncheck the referenced checkbox
        $(checkboxid).prop( 'checked', $(this).is('.green') )
    });