2

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

starball
  • 20,030
  • 7
  • 43
  • 238
rimi
  • 624
  • 5
  • 15
  • 1
    You’re looking for a radio button. This UI/UX pattern not what checkboxes should be used for. – Terry Mar 13 '23 at 03:07
  • I know, but like I mentioned in my original question, I need a check box. This is the requirement – rimi Mar 13 '23 at 03:09
  • 2
    No. Users do not expect checkboxes to work like a radio button. Don't confuse your users. – Tim Roberts Mar 13 '23 at 03:10
  • I wrote this code so that the users dont get confused function reported(checkbox) { var checkboxes = document.getElementsByName('test222') checkboxes.forEach((item) => { if (item !== checkbox) item.checked = false }) } the name of boththe checkbox is test222 – rimi Mar 13 '23 at 03:18
  • I modified my question above so that only one checkbox is clicked. – rimi Mar 13 '23 at 03:21
  • 1
    Radioboxes are the correct answer, and "I want it to be check boxes" is not a sufficient justification. Why do you not want to use the correct tool has to be an important part of the question. I guess someone might have a decent reason why using a chainsaw to eat steak is the only choice, but if you ask "How do I use a chainsaw to eat steak", until you clarify, the only answer you are likely to get is "just use a knife and fork like a normal person, please." – Amadan Mar 13 '23 at 03:32
  • Your code has errors. For example, in your HTML you have checkboxes `#Food1` and `#Food2`, but in your CSS you are looking for classes `.Food1` and `.Food2`. To set the `required` attribute you need to say `.attr('required', true)`, and to remove it, `.attr('required', false)`. – Brett Donald Mar 13 '23 at 03:40

5 Answers5

1

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>
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
1

 $('#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

Mitali Patel
  • 395
  • 2
  • 9
0

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
Brett Donald
  • 6,745
  • 4
  • 23
  • 51
0

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>

  
0

Add the Required on HTML Tag:

<input type="checkbox"  id="Food1" name="test222" required>
Reza Ghorbani
  • 2,396
  • 2
  • 28
  • 33
Deva
  • 97
  • 2