skip to Main Content

I have the following code on my page that has few checkboxes.

<form>
    <input type="checkbox" id="CatFood" /><b>Cat Food</b><br /><br />
    <input type="checkbox"  id="Food1" name="test222" onclick="reported(this)"  />Delicious Food<br />
    <input type="checkbox" id="Food2" name="test222" onclick="reported(this)" />Healthy Food<br /><br /><br />
  
 
    <button type="submit">Submit</button>

</form>
    

Once the user clicks on the CatFood, I want the end user to click on either "Delicious Food" check box or "Healthy Food" check box, but not both. Only One of the check box is required. In order to accomplish this, I tried to write this code:

 <script>
           $(function(){
            $('#CatFood').on('click', function () {
                    if($(this).is(':checked')){

                    $('.Food1').attr('required', 'required') || $('.Food2').attr('required', 'required');
                    }else{

                    $('.Food1').removeAttr('required');
                    }
         
                });
            }); 
   
  

</script>

Nothing is happening on click of the submit button. I can make the checkboxes radio button, but in my case, I want it to be check boxes. below is the screen shot:

enter image description here

below is the code for reported:

function reported(checkbox) {

        var checkboxes = document.getElementsByName('test222')
        checkboxes.forEach((item) => {
            if (item !== checkbox) item.checked = false
        })

    }

I already looked at the following stack overflow link, but that did not help:

GetElement

GetElement2

5

Answers


  1. As a number of people have said in the comments, your “delicious food” and “healthy food” fields should be coded as radio buttons in your HTML, not as checkboxes. That way, you’ll get the correct behaviour without having to do anything.

    However, if you want to, you can style the radio buttons to appear like checkboxes or anything else you like, really. These articles should help you out:

    1. Custom styled radio buttons
    2. Custom styled checkboxes
    Login or Signup to reply.
  2. As some others have pointed out, using radio buttons might be a better option, but if you really want to use checkboxes, the code below can help you achieve your goal,

    <form>
      <input type="checkbox" id="catFood" onclick="makeCatFoodsRequired(this)" />
      <b>Cat Food</b><br /><br />
      <input type="checkbox" id="food1" class="catFoods" name="food" onclick="clearOtherCatFoods(this)" />
      Delicious Food <br />
      <input type="checkbox" id="food2" class="catFoods" name="food" onclick="clearOtherCatFoods(this)" />
      Healthy Food<br />
      <br /><br />
      <button type="submit">Submit</button>
    </form>
    
    <script>
      function makeCatFoodsRequired(checkbox) {
        const catFoods = document.querySelectorAll('.catFoods');
    
        if (checkbox.checked) {
          catFoods.forEach(food => food.required = true);
        } else {
          catFoods.forEach(food => food.required = false);
        }
      }
    
      function clearOtherCatFoods(checkbox) {
        const catFoods = document.querySelectorAll('.catFoods');
    
        catFoods.forEach(food => {
          if (food !== checkbox) {
            food.checked = false;
            food.required = false;
          } else {
            food.required = true;
          }
        });
      }
    </script>
    Login or Signup to reply.
  3. Please try this updated

    <form>
        <input type="checkbox" id="CatFood1" onclick="reported1(0)""/><b>Cat Food</b>
        <br />
        <br />
        <input type="checkbox" id="Food11"   name="test2221" required   onclick="reported1(1)" />Delicious Food
        <br />
        <input type="checkbox" id="Food22"   name="test2222" required onclick="reported1(2)" />Healthy Food
        <br />
        <br />
        <br />
    
    
        <button type="submit" onclick="return submitBtn1();">Submit</button>
    
    </form>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    function submitBtn1() {
    
        var catFood = $('#CatFood1').is(":checked");
        var food1 = $('#Food11').is(":checked");
        var food2 = $('#Food22').is(":checked");
        if (catFood == true) {
            if (food1 == true || food2 == true) {
                return true;
            }
            else {
                //$('#Food11').attr("required", true);
                ////$('#Food11,#Food22').removeAttr("required", false);
                //return false;
            }
        }
        else {
            $('#Food11,#Food22').removeAttr("required", true);
        }
    }
    
    function reported1(type) {
        if (type == 0)
        {
            if ($('#CatFood1').is(":checked") == true) {
     if ($('#Food11').is(":checked") == false && $('#Food22').is(":checked") == false)
                $('#Food11,#Food22').attr("required", true);
            }
            else {
                $('#Food11,#Food22').removeAttr("required", true);
            }
        }
       else if (type == 1) {
            if ($('#Food11').is(":checked") == true) {
                $('#Food22').prop("checked", false);
                $('#Food22').removeAttr("required", true);
            }
        }
        else {
            if ($('#Food22').is(":checked") == true) {
                $('#Food11').prop("checked", false);
                $('#Food11').removeAttr("required", true);
    
            }
        }
    }
    </script>

    Please Try this

       function submitBtn() {
            var catFood = $('#CatFood').is(":checked");
            var food1 = $('#Food1').is(":checked");
            var food2 = $('#Food2').is(":checked");
            if (catFood == true) {
                if (food1 == true || food2 == true) {
                    alert("submit success");
                    return true;
                }
                else {
                    alert("Please select one Food or Healthy Food");
                    return false;
                }
            }
        }
    
        function reported(type) {
            if (type == 1) {
                if ($('#Food1').is(":checked") == true) {
                    $('#Food2').prop("checked", false);
                }
            }
            else {
                if ($('#Food2').is(":checked") == true) {
                    $('#Food1').prop("checked", false);
                }
            }
        }
    <input type="checkbox" id="CatFood" /><b>Cat Food</b>
    <br />
    <br />
    <input type="checkbox" id="Food1" name="test222" onclick="reported(1)" />Delicious Food
    <br />
    <input type="checkbox" id="Food2" name="test222" onclick="reported(2)" />Healthy Food
    <br />
    <br />
    <br />
    
    
    <button type="submit" onclick="return submitBtn();">Submit</button>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
      
    Login or Signup to reply.
  4.  $('#formmaster').parsley();
     function submitBtn() {
          $('#formmaster').parsley().validate();
          if ($('#formmaster').parsley().isValid()) 
          {
            var catFood = $('#CatFood').is(":checked");
            var food1 = $('#Food1').is(":checked");
            var food2 = $('#Food2').is(":checked");
            if (catFood == true) {
                if (food1 == true || food2 == true) {
                    return true;
                }
                else {
                    return false;
                }
            }
          }
        }
    
      function reported(type) {
          if (type == 1) {
              if ($('#Food1').is(":checked") == true) {
                  $('#Food2').prop("checked", false);
                  $('#Food1').attr('required','required');
                  $('#CatFood').prop("checked", true);
              }
          }
          else {
              if ($('#Food2').is(":checked") == true) {
                  $('#Food1').prop("checked", false);
                  $('#Food2').attr('required','required');
                  $('#CatFood').prop("checked", true);
              }
          }
      }
    p.parsley-success {
      color: #468847;
      background-color: #DFF0D8;
      border: 1px solid #D6E9C6;
    }
    
    p.parsley-error {
      color: #B94A48;
      background-color: #F2DEDE;
      border: 1px solid #EED3D7;
    }
    
    input.parsley-success,
    select.parsley-success,
    textarea.parsley-success {
      color: #468847;
      background-color: #DFF0D8;
      border: 1px solid #D6E9C6;
    }
    
    input.parsley-error,
    select.parsley-error,
    textarea.parsley-error {
      color: #B94A48;
      background-color: #F2DEDE;
      border: 1px solid #EED3D7;
    }
    
    .parsley-errors-list {
      margin: 2px 0 3px;
      padding: 0;
      list-style-type: none;
      font-size: 0.9em;
      line-height: 0.9em;
      opacity: 0;
      transition: all .3s ease-in;
      -o-transition: all .3s ease-in;
      -moz-transition: all .3s ease-in;
      -webkit-transition: all .3s ease-in;
    }
    
    .parsley-errors-list.filled {
      opacity: 1;
    }
    
    .parsley-required {
      font-size: 12px;
      color: #eb2420;
    }
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.7.2/parsley.min.js"></script>
    <form id="formmaster">
      <input type="checkbox" id="CatFood" data-parsley-required-message="Please select one Food or Healthy Food" required/><b>Cat Food</b>
      <br />
      <br />
      <input type="checkbox" id="Food1" name="test222" onclick="reported(1)" />Delicious Food
      <br />
      <input type="checkbox" id="Food2" name="test222" onclick="reported(2)" />Healthy Food
      <br />
      <br />
      <br />
      <button type="submit" onclick="return submitBtn();">Submit</button>
    </form>

    Please try this code. I have used Form validation with Parsley

    Login or Signup to reply.
  5. Add the Required on HTML Tag:

    <input type="checkbox"  id="Food1" name="test222" required>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search