1

This is a fragment of my code. Can I add an ID to this portion? Now I have 2 groups of check boxes (topic, interests). When I check the box in the group and I do not check the box in the second group, an error message appears.

My idea: add ID to this "input [type = checkbox]: selected" and add all of it to IF. Is it possible to do it ?

Under the text is my idea what it should look like:

#I know it doesn't work. 
if(($('input[type=checkbox][id=subject]:checked').length == 0) && $('input[type=checkbox][id=interests]:checked').length == 0))
<script>
function validate_form()
{
    valid = true;
    if($('input[type=checkbox]:checked').length == 0)
{
    document.getElementById("status").innerHTML = "Please tick one box for interests and topics";
    valid = false;
}

    return valid;
}
</script>
2
  • Can you also share the html? Commented May 8, 2020 at 17:42
  • Also it would be helpful to others if you could provide the error code. As you mentioned you have one. Commented May 8, 2020 at 17:49

1 Answer 1

2

I suggest the following steps:

  • add attribute class for group's checkboxes

  • add div for every block of interests and set id depending on the group id

  • on validate, get interests div block by checked group id

Like this:

$('.group:checked').each(function() {
    const groupInterestsId = `#${this.id}Interests`
    if ($(`${groupInterestsId} input[type="checkbox"]:checked`).length === 0) {
    alert('Please select interests for selected group')
    return false;
  }
})

See full example on my sandbox: https://jsfiddle.net/denisstukalov/bosqhruf/34/#&togetherjs=60jflqRT4b

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

Comments

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.