Home > OS >  Setting a limit for checkbox in js
Setting a limit for checkbox in js

Time:03-05

I'm trying to make a form that sets a limit for 3 selection max or 1 minimum for my checkbox. I do get the error message once the condition isn't set but I still can check them. How can I prevent that? and how can I prevent it from submitting the form when it happens?

This is my JavaScript code

function Calculate() {
    var a = document.getElementsByName("vehicle");
    var n = 0;
    var count;
    for (count = 1; count < a.length; count  ) {
        if (a[count].checked === true) {
            n = n   1;
        }
    }
    if (n > 4 || n == 0) {
        document.getElementById('er').innerHTML =
            'Please Select atleast one car or 3 at most ';
        sp.style.visibility = 'visible';

        return false;
    }
}

this is my html code structure:

  <p >
    Please Fill The Form Carefully
  </p>
</div>

<form name="Drive-form"  onsubmit="val()" method="GET" action="success.html" >
  <div >
    <label>Full Name</label>
    <input name="name" type="text"
      placeholder="First and Last Name" />
    <div >Name is required</div>
  </div>

 

  <div >
    <label>Phone</label>
    <input name="phone" type="text"
    ></input>
    <div >Phone is invalid</div>
  </div>

 
  <div >
   
    <p>Please select your preferred contact method:</p>
    <div>
      <input type="radio" id="Choice1"
       name="age" value="18-25">
      <label for="Choice1">18-25</label>
  
      <input type="radio" id="Choice2"
       name="age" value="25-30">
      <label for="Choice2">25-30</label>
  
      <input type="radio" id="Choice3"
       name="age" value="30>">
      <label for="Choice3">30></label>
    </div>
    <div>

  </div>
  <br>

  <div >
   
    <p>Please select at least 3 cars:</p> <br>

        <input type="checkbox" id="vehicle" name="vehicle" value="Mazda" onclick= " Calculate();">
 <label for="vehicle1"> Mazda </label><br>
 <input type="checkbox" id="vehicle2" name="vehicle" value="Honda" onclick= " Calculate();" >
 <label for="vehicle2"> Honda </label><br>
 <input type="checkbox" id="vehicle3" name="vehicle" value="BMW" onclick= " Calculate(); ">
 <label for="vehicle3"> BMW</label><br>
 <input type="checkbox" id="vehicle4" name="vehicle" value="Toyota" onclick= " Calculate(); ">
 <label for="vehicle4"> Toyota </label><br>
 <input type="checkbox" id="vehicle5" name="vehicle" value="Jeep" onclick= " Calculate(); ">
 <label for="vehicle5"> Jeep </label><br>
 <input type="checkbox" id="vehicle6" name="vehicle" value="GMC" onclick= " Calculate(); ">
 <label for="vehicle6"> GMC </label><br> 

<span id="er"></span> 
      </div>



      <hr />

      <button type="submit">SUBMIT FORM</button>
      <button type="reset">RESET FORM</button>
    </form>

CodePudding user response:

The fixed code:

function Calculate(){ 
    var a = document.getElementsByName("vehicle");
    var n = 0;
    var count;
    for(count=0; count<a.length;count  ){
if(a[count].checked===true){
n=n 1;

}

    }
    if(n > 3||n==0){
    event.preventDefault();
document.getElementById('er').innerHTML='Please Select atleast one car or 3 at most ';


return false;

    }
    
};
<form >
<input type = "checkbox" name = "vehicle">
<input type = "checkbox" name = "vehicle">
<input type = "checkbox" name = "vehicle">
<input type = "checkbox" name = "vehicle">
<input type  = "submit" value = "Submit "onclick = "Calculate()">

</form>
<p id = "er">

</p>

if()s

First, the count = 1 should be count = 0 because it will stop at 1 less than the total number of checks.

n > ?

First, if you want it to be min: 1 and max:3, first you need n < or = to 3 so if not it has to be n > 3 instead of n > 4

document.getElementById()

That is where it should be. But if you want it to send to server, then put in there event.preventDefault(); because it prevents the server from submitting it when you don't want it to.

CodePudding user response:

I'd suggest you check for change event for your form element to check the total number of checked items each time a selection is made. In the handler function you can validate the proper number of selections and determine whether to disable the button and prohibit submission.

See the code snippet below.

const form = document.querySelector('form.pet-form');
const fields = form.querySelectorAll('input');
const button = form.querySelector('button.submit');
const msg = form.querySelector('.message');

form.addEventListener('change', validateForm);
form.addEventListener('submit', handleSubmit);

function validateForm() {
  let boxCount = 0;
  fields.forEach(field => field.checked ? boxCount   : null);
  if (boxCount > 3 || boxCount <1) { 
    msg.innerText = "Please select 1–3 animals.";
    msg.style.backgroundColor = '#FFE0E0'
    button.disabled = true;
  } else {
    msg.innerText = "Ready to submit!";
    button.disabled = false;
    msg.style.backgroundColor = '#E0E0E0'
  }
}

function handleSubmit(e) {
  e.preventDefault(); // prevent page reload;
  alert('Submitted the form'); // do what you need to do to submit
}
label {
  cursor: pointer;
}

button {
  padding: 1em 2em;
}

.message {
  padding: 1em;
  background: #FFE0E0;
  margin: 1em 0;
}
<form >
  <div >
    <h2>Choose your pets</h2>
    <label for="dog">
      <input type="checkbox" id="dog" name="pet">
        Dog
      </label>
    <label for="cat">
      <input type="checkbox" id="cat" name="pet">
        Cat
      </label>
    <label for="duck">
      <input type="checkbox" id="duck" name="pet">
        Duck
      </label>
    <label for="moose">
      <input type="checkbox" id="moose" name="pet">
        Moose
      </label>
    <label for="dragon">
      <input type="checkbox" id="dragon" name="pet">
        Dragon
      </label>
  </div>
  <div >Please select 1–3 animals.</div>
  <div >
    <button  disabled>Submit</button>
  </div>
</form>

  • Related