Search code examples
javascriptformsvalidationverification

Javascript - Compare if any checkbox is marked or not


Sure that here are many solutions for this problem, but I did not find a solution for me.

I have a form with several checkboxes to choose an option (radio1a, radio1b,radio1c,etc), but I cannot detect if my user has not checked a box, before submit the form.

I have tried the sample script, but the alerts are loaded with the page, and it is not what I am looking for.

Note: The "checked" option (for any checbox), is not a possibility for me, I have to leave all boxes unchecked.

What am I doing wrong here?

Thanks in advance!


HTML:

<input id="radio1a" class="radiosobres" type="radio" name="radio" value="something>

<input id="radio1b" class="radiosobres" type="radio" name="radio" value="something>

<input id="radio1c" class="radiosobres" type="radio" name="radio" value="something>

<input id="radio1d" class="radiosobres" type="radio" name="radio" value="something>

<input id="radio1e" class="radiosobres" type="radio" name="radio" value="something>

<!-- ============== -->

<input id="pedir-sobres" type="submit" value="Pedir"/>

Script Test:

// ===========

jQuery 2.2.4

// ===========

$(".radiosobres").each(function () {
var id = $(this).attr("id");
if ($("#" + id).is(":not(:checked)")) {
alert("something...");
}
});

Solution

  • I set on every radiobutton an clickevent which adds a class clicked to it. So if you click the submit-button I can check which of the radios has the clicked-class and you can act for this.

    $(".radiosobres").click( function() {
        $(this).addClass('clicked');
        }
    )
    
    $('#pedir-sobres').click(function() {
        let checkOk = false;
        $(".radiosobres").each(function () {
          if ( $(this).hasClass('clicked') ) {
            checkOk = true;
          }
        })
        
        if (!checkOk) {
          alert('Not all radios checked');
          return false;
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <form>
    <input id="radio1a" class="radiosobres" type="radio" name="radio" value="something">
    <input id="radio1b" class="radiosobres" type="radio" name="radio" value="something">
    
    <input id="radio1c" class="radiosobres" type="radio" name="radio" value="something">
    
    <input id="radio1d" class="radiosobres" type="radio" name="radio" value="something">
    
    <input id="radio1e" class="radiosobres" type="radio" name="radio" value="something">
    
    <!-- ============== -->
    
    <input id="pedir-sobres" type="submit" value="Pedir"/>
    </form>