jeudi 18 juillet 2019

Get all checkboxes and check them by previous sibling

I have a code like this:

<div class="elements" id="elements">
    <span>
        <span>Check anyone (required)</span>
    </span>
    <input type="checkbox" name="vehicle" value="minivan"> Minivan
    <input type="checkbox" name="vehicle" value="car"> Car
    <input type="checkbox" name="vehicle" value="boat"> Boat

    <span>
        <span>Check anyone</span>
    </span>
    <input type="checkbox" name="sport" value="basketball"> Basketball
    <input type="checkbox" name="sport" value="soccer"> Soccer
    <input type="checkbox" name="sport" value="tennis"> Tennis
</div>

<button id="check">Check</button>

<script>
    document.getElementById("check").onclick = function () {
        // Check it all... if required text is found and at least one checkbox is not found for that specific checkbox name, then throw alert
    }
</script>

I want to check all checkboxes in the div class/id elements and then check the previous span span tag and if there is a "required" text, then make sure one at least one checkbox is selected.

For example, let's start with checkbox name="vehicle". We reference/look back in the previous sibling <span><span> and we see if the text "required" exists. If it does exist, we need to make sure at least checkbox of name=vehicle is checked. If not, we need to `alert('error! please check a checkbox');

For example in name="sport", we do not have to check if at least one checkbox is checked because the text "required" does not exist in previous span span.

I know its weird but it has to be like this - just need to work with it. any help? thanks everyone!




Aucun commentaire:

Enregistrer un commentaire