Estoy tratando de crear un formulario que requiere que se seleccionen al menos dos casillas de verificación. He intentado todo lo que pude encontrar sin ningún tipo de éxito.
function cb_require() { let chckbx = document.forms['form_name']['contact'].value; for (chckbx.length === 1) { if (i = 0; i < chckbx.length; i++) { alert('check 2'); return false; } } } <form method="post" name="form_name" id="form_name" action="mailto:bb@yahoo.com" enctype="text/plain" onsubmit="return cb_require()"> <label for="cont">Preferred Contact Method:</label> <input type="checkbox" id="Phone" name="contact" value="Phone"> <label for="Phone">Phone</label> <input type="checkbox" id="E-mail" name="contact" value="E-email"> <label for="E-mail">E-mail</label><br> <input type="checkbox" id="Mail" name="contact" value="Mail"> <label for="Mail">Mail</label> <input type="checkbox" id="LinkedIn" name="contact" value="LinkedIn"> <label for="LinkedIn">LinkedIn</label><br><br> </form>Gracias de antemano por cualquier ayuda o consejo!
Puede usar simplemente querySelectorAll para filtrar solo la checkbox checked , si la length es igual a dos submit de envío como:
const form = document.querySelector('#form_name'); form.addEventListener('submit', (e) => { e.preventDefault(); let chckboxs = form.querySelectorAll('input[type="checkbox"]:checked'); if (chckboxs.length > 1) { console.log('form submit'); } else { console.log('error form'); } }); <form method="post" name="form_name" id="form_name" action="mailto:bb@yahoo.com" enctype="text/plain"> <label for="cont">Preferred Contact Method:</label> <input type="checkbox" id="Phone" name="contact" value="Phone"> <label for="Phone">Phone</label> <input type="checkbox" id="E-mail" name="contact" value="E-email"> <label for="E-mail">E-mail</label><br> <input type="checkbox" id="Mail" name="contact" value="Mail"> <label for="Mail">Mail</label> <input type="checkbox" id="LinkedIn" name="contact" value="LinkedIn"> <label for="LinkedIn">LinkedIn</label><br><br> <button type="submit">ClickMe</button> </form>Referencia: