2012-08-03 15 views
17

Ho un modulo con più checkbox e voglio usare JavaScript per assicurarmi che almeno uno sia selezionato. Questo è quello che ho adesso ma non importa quale sia la scelta di un avviso.Verifica che almeno una casella di controllo sia selezionata

JS (sbagliato)

function valthis(){ 
if (document.FC.c1.checked) { 
    alert ("thank you for checking a checkbox") 
    } else { 
    alert ("please check a checkbox") 
    } 
} 

HTML

<p>Please select at least one Checkbox</p> 
<br> 
<br> 
<form name = "FC"> 
<input type = "checkbox" name = "c1" value = "c1"/> C1 
<br> 
<input type = "checkbox" name = "c1" value = "c2"/> C2 
<br> 
<input type = "checkbox" name = "c1" value = "c3"/> C3 
<br> 
<input type = "checkbox" name = "c1" value = "c4"/> C4 
<br> 
</form> 
<br> 
<br> 

<input type = "button" value = "Edit and Report" onClick = "valthisform();"> 

Quindi quello che ho finito per fare in JS è stato questo:

function valthisform(){ 
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked 

if (chkd == true){ 

} else { 
    alert ("please check a checkbox") 
} 

} 

Ho deciso di abbandonare la parte "Grazie" per adattarla al resto del compito. Grazie mille, ogni consiglio mi è stato di grande aiuto.

+0

Perché il pulsante "Modifica e segnala" * al di fuori * del modulo? –

risposta

20

È consigliabile evitare due caselle con lo stesso nome se si intende fare riferimento ad esse come document.FC.c1. Se hai più caselle di controllo denominate c1, in che modo il browser saprà a chi ti stai riferendo?

Ecco una soluzione non jQuery per controllare se sono spuntate le caselle di controllo nella pagina.

var checkboxes = document.querySelectorAll('input[type="checkbox"]'); 
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked); 

È necessario la parte Array.prototype.slice.call per convertire il NodeList restituito da document.querySelectorAll in una matrice che è possibile chiamare some on.

+0

Grazie, stavo cercando di evitare il JQuery ma il tuo secondo suggerimento ha aiutato un bel po ' – MegaSly

+13

@Mash 'Non dovresti mai avere due elementi con lo stesso nomi CHE COSA ????? Allora come si scrive? le radio? – Mageek

+2

* "Evitare di avere due elementi con lo stesso nome" * - Sbagliato. L'uso di nomi di elementi duplicati è valido, funziona su tutti i browser e funziona bene sul lato server una volta inviato il modulo. Come ha detto Mageek, è come si creano gruppi radio, ma è valido anche con altri elementi del modulo. – nnnnnn

18

Questo dovrebbe funzionare:

function valthisform() 
{ 
    var checkboxs=document.getElementsByName("c1"); 
    var okay=false; 
    for(var i=0,l=checkboxs.length;i<l;i++) 
    { 
     if(checkboxs[i].checked) 
     { 
      okay=true; 
      break; 
     } 
    } 
    if(okay)alert("Thank you for checking a checkbox"); 
    else alert("Please check a checkbox"); 
} 

Se hai una domanda sul codice, basta lasciare un commento.


Io uso l=checkboxs.length per migliorare le prestazioni. Vedere http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

+0

Grazie. Stavo cercando su come validare le checkbox e questo ha funzionato per me – user1815823

+0

Sono stato costretto con questo problema, ma il tuo codice ha risolto il mio problema +1 – offboard

+2

Una pausa dopo "okay = true" ottimizzerà un po ': P –

2

Check this.

Non è possibile accedere input di form tramite il loro nome. Utilizzare invece i metodi document.getElements.

1

Utilizzando jQuery, sotto puoi semplicemente impedire all'utente di deselezionare l'ultima casella selezionata.

$('input[type="checkbox"][name="chkBx"]').on('change',function(){ 
 
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){ 
 
    return this.value; 
 
    }).toArray(); 
 
    
 
    if(getArrVal.length){ 
 
    //execute the code 
 
    $('#cont').html(getArrVal.toString()); 
 
    
 
    } else { 
 
    $(this).prop("checked",true); 
 
    $('#cont').html("At least one value must be checked!"); 
 
    return false; 
 
    
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<label> 
 
    <input type="checkbox" name="chkBx" value="value1" checked> Value1 
 
</label> 
 
<label> 
 
    <input type="checkbox" name="chkBx" value="value2"> Value2 
 
</label> 
 
<label> 
 
    <input type="checkbox" name="chkBx" value="value3"> Value3 
 
</label> 
 

 
<div id="cont"></div>

0
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > </script > 
    < script type = "text/javascript" > 

function checkSelectedAtleastOne(clsName) { 
    if (selectedValue == "select") 
     return false; 

    var i = 0; 
    $("." + clsName).each(function() { 

     if ($(this).is(':checked')) { 
      i = 1; 
     } 

    }); 

    if (i == 0) { 
     alert("Please select atleast one users"); 
     return false; 
    } else if (i == 1) { 
     return true; 
    } 

    return true; 

} 

$(document).ready(function() { 
    $('#chkSearchAll').click(function() { 

     var checked = $(this).is(':checked'); 
     $('.clsChkSearch').each(function() { 
      var checkBox = $(this); 
      if (checked) { 
       checkBox.prop('checked', true); 
      } else { 
       checkBox.prop('checked', false); 
      } 
     }); 

    }); 

    //for select and deselect 'select all' check box when clicking individual check boxes 
    $(".clsChkSearch").click(function() { 

     var i = 0; 
     $(".clsChkSearch").each(function() { 

      if ($(this).is(':checked')) {} 
      else { 

       i = 1; //unchecked 
      } 

     }); 

     if (i == 0) { 
      $("#chkSearchAll").attr("checked", true) 
     } else if (i == 1) { 

      $("#chkSearchAll").attr("checked", false) 
     } 

    }); 

}); 

</script > 
1

Vanilla JS:

var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable 

function activitiesReset() { 
    var checkboxesChecked = function() { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false. 
     for (var i = 0; i < checkboxes.length; i++) { 
      if (checkboxes[i].checked) { 
       return true; 
      } 
     } 
     return false; 
    } 
    error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead. 
     if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked 
      error[2].style.display = 'block'; // red error label is now visible. 
     } 
} 

for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs. 
    checkboxes[i].addEventListener('change', activitiesReset); 
} 


Spiegazione:
Una volta che un modulo per presentare le è stata tentata, questo aggiornerà il capitolo casella di controllo' s etichetta per notificare all'utente di selezionare una casella di controllo se non lo ha ancora fatto. Se non viene selezionata alcuna casella di controllo, viene visualizzata un'etichetta di "errore" nascosta che richiede all'utente di selezionare la casella di controllo. Se l'utente controlla almeno una casella di controllo, l'etichetta rossa viene istantaneamente nascosta nuovamente, rivelando l'etichetta originale. Se l'utente disattiva nuovamente tutte le caselle di controllo, l'etichetta rossa ritorna in tempo reale. Ciò è reso possibile da eventi di JavaScript onchange (scritto come .addEventListener('change', function(){});

0

È possibile verificare che almeno uno casella è selezionata o non utilizzo di questo semplice codice. Si può anche cadere il vostro messaggio.

Riferimento Link

<label class="control-label col-sm-4">Check Box 2</label> 
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br /> 
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br /> 

<script> 
function checkFormData() { 
    if (!$('input[name=checkbox2]:checked').length > 0) { 
     document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null"; 
     return false; 
    } 
    alert("Success"); 
    return true; 
} 
</script> 
Problemi correlati