Dipak
Dipak

Reputation: 939

jquery if checkbox is not selected

What is wrong in following jquery code ? If the menu which contains value 1 is selected, at least one submenu must be checked.

It is not working, if submenu is checked, still it alert message and is stopping. I am trying adding [name='submenu[]'] or storing value in variable but it doesn't work.

if ($("[name='menu[]']:checked").val() == 1) {
  if ($("[name='submenu[][]']:checked").length == 0) {
    alert('Select at least one submenu ');
    return false;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><input type="checkbox" name="menu[]" value="1">News
    <ul>
      <li><input type="checkbox" name="submenu[1][]" value="1">Local</li>
      <li><input type="checkbox" name="submenu[1][]" value="2">National</li>
    </ul>
  </li>
  <li><input type="checkbox" name="menu[]" value="2">Views</li>
  <li><input type="checkbox" name="menu[]" value="3">Comment</li>
</ul>

Upvotes: 1

Views: 691

Answers (2)

Prashanth
Prashanth

Reputation: 45

BY looking at you code what i understand is that you want to validate that atleast one checkbox must be cheked

give same class to similar check boxes like,

<li><input type="checkbox" class="submenuCkeckbox" name="submenu[1][]" value="1">Local</li>
<li><input type="checkbox"  class="submenuCkeckbox" name="submenu[1][]" value="2">National</li>

in the validating function have a flag by default it will be set to false and that flag will be set if atleast one is cheked

function validate(){
    var alertFlag = false;

    $(".submenuCkeckbox").each(function () {
        if ($(this).is(':checked')) {
            alertFlag = true;
        }
    });

    if (!alertFlag ) {
        alert('Select Atleast one checkbox');
    }
}

Upvotes: 0

Bhumi Shah
Bhumi Shah

Reputation: 9474

You can do it this way : https://codepen.io/creativedev/pen/aKwJGW

$(document).ready(function() {
  $('input[type="checkbox"]').click(function () {
      if ($("[name='menu[]']:checked").val() == 1) {
                console.log($("[name^='submenu']:checked").length);
        if ($("[name^='submenu']:checked").length == 0) {
          alert('Select at least one submenu ');
          //return false;
        }
      }
    });
});

Upvotes: 1

Related Questions