Validate if there is one or several checkboxes selected in Javascript

0

Sometimes they ask us in a form of HTML , list in 1 or n checkboxes characteristics of an element. Example:

Select 1 or n areas of interest for your job application.

Then we must obtain the C / U ID of the areas of interest that you select and validate if at least 1 checkbox has been selected.

How do I do it?

    
asked by Ricardo Sauceda 25.05.2018 в 23:19
source

2 answers

1

So to solve this problem I did the following:

These checkboxes are ready dynamically. I get everything directly from the database.

In my form I have:

<div class="w-row">
   <% for (int i = 0; i < areaInteresModel.length; i++) {
      CatAreaInteresModel areaInteres = CatAreaInteresModel[i];
   %> 
   <div class="w-col w-col-3">
        <div class="w-form">
             <input type="checkbox" id="<%=areaInteres.getcAreaInteresId()%>" data-name="checkbox" name="checkbox"  value="<%=areaInteres.getcAreaInteresId()%>" > <%=areaInteres.getcAreaInteresNombre()%>                                     
        </div>
   </div>
   <%}%>

And in Javascript

var check_interes = form_t.checkbox_t; //Array que contiene los checkbox
    var cont_t = 0; //Variable que lleva la cuenta de los checkbox pulsados    
    for (var x = 0; x < check_interes.length; x++) {
        if (check_interes[x].checked) {
            cont_t = cont_t + 1;
        }
    }

if (cont_t == 0) {
    //SINO HA SELECCIONADO
    alert("ERROR");
    return false;
} else if (cont_t > 5) {
    //SINO HA SELECCIONADO MAS DE (5 o N) OPCIONES DISPONIBLES.
    alert("ERROR");
    return false;
} 


var interes = document.forms[2];
var area_interes = "";
var i;
for (i = 0; i < interes.length; i++) {
    if (interes[i].checked) {
        //OBTENEMOS UN STRING CON TODOS LOS ID DE NUESTRO CHECKBOX
        area_interes = area_interes + interes[i].value + ",";
    }
}

I hope you serve them, help them and I hope to be brief and concise with my contribution. If not, suggest a better solution, greetings!

    
answered by 25.05.2018 в 23:35
0

This could be useful

//this es el formulario
let checked = this.querySelectorAll('input[type=checkbox]:checked');
if (checked.length == 0) {
    //SINO HA SELECCIONADO
    alert("ERROR");
    return false;
} else if (checked.length > 5) {
    //SINO HA SELECCIONADO MAS DE (5 o N) OPCIONES DISPONIBLES.
    alert("ERROR");
    return false;
} 

let area_interes = "";
for (let i = 0, length = checked.length; i < length; i++) {
    area_interes += checked[i].value + ",";             
}
    
answered by 09.06.2018 в 00:04