简体   繁体   中英

How to check if any value is saved in an array after selecting multiple checkboxes

I have been working on the following form where a user can register to a website as a player or a coach. In here, I want to check if the user has selected at least one sport and if not, the form should alert the user prompting to select one sport. The html code is as follows.

 <form action="" name="userForm" method="POST" onsubmit="return upassword()" enctype="multipart/form-data"> <table cellspacing="2" cellpadding="2" border="0" > <tr> <td colspan="5"> <p>First Name</p> <input type="text" placeholder="First Name" name="Fname" required> </td> <td colspan="5"> <p>Last Name</p> <input type="text" placeholder="Last Name" name="Lname" required> </td> </tr> <tr> <td colspan="10"> <p>Profile Picture</p> <input type="file" name="Pimage" required> </td> </tr> <tr> <td colspan="10"> <p>Gender</p> </td> </tr> <tr> <td></td> <td> <input type="radio" name="Gender" value="Male"> </td> <td> <label>Male</label> </td> <td> <input type="radio" name="Gender" value="Female"> </td> <td> <label>Female</label> </td> <td colspan="5"></td> </tr> <tr> <td colspan="10"> <p>Sports</p> </td> </tr> <tr> <td></td> <td> <input type="checkbox" name="Sport[]" value="Squash"> </td> <td> <label>Squash</label> </td> <td> <input type="checkbox" name="Sport[]" value="Tennis"> </td> <td> <label>Tennis</label> </td> <td> <input type="checkbox" name="Sport[]" value="Badminton"> </td> <td> <label>Badminton</label> </td> <td> <input type="checkbox" name="Sport[]" value="Archery"> </td> <td> <label>Archery</label> </td> <td></td> </tr> <tr> <td colspan="10"> <p>Username</p> <input type="text" placeholder="Username" name="Username" required> </td> </tr> <tr> <td colspan="5"> <p>Password</p> <input type="password" placeholder="10-20 characters including @, #, $, %, &" name="Password" pattern="[a-zA-Z0-9%@#$&]{10,20}" required> </td> <td colspan="5"> <p>Re-enter password</p> <input type="password" placeholder="Re-enter password" name="RPassword" required> </td> </tr> <tr> <td colspan="10" align="center"> <br/> <p>User Type</p> </td> </tr> <tr> <td colspan="3"></td> <td> <input type="radio" name="User" value="Player"> </td> <td> <label>Player</label> </td> <td> <input type="radio" name="User" value="Coach"> </td> <td> <label>Coach</label> </td> <td colspan="3"></td> </tr> <tr> <td colspan="10"><br/></td> </tr> <tr> <td colspan="3"></td> <td> <input type="checkbox" id="userAgree" name="userAgree" onclick="usubmitenable()"> </td> <td colspan="6"> <label>I agree to the terms and conditions.</label> </td> </tr> <tr> <td colspan="10"><br/></td> </tr> <tr align="center"> <td colspan="5"> <button type="submit" id="usersbt" value="Submit" disabled>Submit</button> </td> <td colspan="5"> <button type="reset" value="Reset" style="background-color:#a32626;">Reset</button> </td> </tr> </table> </form>

For the validation part, I have used the following JavaScript functions.

 function upassword(){ var a=document.userForm.Password.value; var b=document.userForm.RPassword.value var c=document.userForm.Gender.value; var e=document.userForm.User.value; var f= new Array(); f=document.userForm.Sport[].value; if(c=="") { alert("Please Select Gender!"); return false; } else if(e=="") { alert("Please Select User Type!"); return false; } else if(f.length == 0) { alert("Please Select Sport!"); return false; } else if(a!=b) { alert("Passsword Mismatch!"); return false; } else { return( true ); } } function usubmitenable(){ if(document.getElementById("userAgree").checked) { document.getElementById("usersbt").disabled = false; } else { document.getElementById("usersbt").disabled = true; } }

The validations works fine if I comment out the part where I check if any of the checkboxes have been checked. Else, the code does not work. How can I fix this problem? Please help, thankyou!

So I found a code snippet online and changed it according to my form and it worked fine. Thankyou for helping! Here is the code.

 var checkboxs = document.getElementsByName('Sport[]'); var okay = 0; for (var i = 0, l = checkboxs.length; i < l; i++) { if (checkboxs[i].checked) { okay = 1; break; } } if (okay == 0) { alert("Please Select Sport!"); return false; }

Every checkbox has its own individual value, so value on a collection of checkboxes with a name -attribute will not work.

Using the right css selector, you can create an array of checked checkboxes values, for example:

 document.addEventListener(`click`, handle); function handle(evt) { if (evt.target.type === `checkbox`) { const allChecked = document.querySelectorAll(`[type='checkbox']:checked`); // ^ all checked checkboxes if (allChecked.length < 1) { return document.querySelector(`#checkValid`).click(); } document.querySelector(`#currentlySelected`).textContent = `selected: ` + [...allChecked].map(v => v.value).join(`, `); } if (evt.target.id === `checkValid`) { if (document.querySelectorAll(`[type='checkbox']:checked`).length < 1) { const result = document.querySelector(`#currentlySelected`); result.textContent = ``; document.querySelector(`#currentlySelected`).insertAdjacentHTML(`beforeend`, `<b style="color:red">It's time to select a sport</b>`); } } }
 <div> <div><input type="checkbox" value="Squash">Squash</div> <div><input type="checkbox" value="Tennis">Tennis</div> <div><input type="checkbox" value="Badminton">Badminton</div> <div><input type="checkbox" value="Archery">Archery</div> <p id="currentlySelected"></p> <button id="checkValid">Check</button> </div>

You can use in this case the getElementsByName Selectorhelper. And the you fetch the array. You can use an for loop to make a string with all selected sporttypes.

    f=document.getElementsByName('Sport[]');
    let values = ''
    for (var i=0, n=f.length;i<n;i++) 
    {
        if (f[i].checked) 
        {
            values += ","+f[i].value;
        }
    }
    if (values) values = values.substring(1);    
    console.log(values)

You can refer following link and a comment to a different question to do it with minimal code. Use javascript to set all checkboxes as required unless there is one already checked. If none of the checkbox is selected then all will be set as required.

https://stackoverflow.com/a/38845805/7483085

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM