jQuery validation to select at least one checkbox - javascript

I have written following code to select multiple checkbox and also need to validate at least one checkbox is selected. In the following code data submission to database is working if I remove onsubmit="return validate_form()". But I want to validate at least one checkbox is selected.
Following is the code:
<?php
$link=mysql_connect("localhost","root","") or die("cant connect");
mysql_select_db("country_ajax",$link) or die("cant select db");
extract($_POST);
$check_exist_qry="select * from language";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_language=explode(',',$my_value['language_name']);
}
if(isset($submit))
{
$fname=$_POST['fname'];
$sname=$_POST['sname'];
$all_language_value = implode(",",$_POST['language']);
if($total_found >0)
{
//update
$upd_qry="UPDATE language SET language_name='".$all_language_value."' where member_id = 75";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO language(language_name) VALUES('".$all_language_value."') where member_id = 75";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="" onsubmit="return validate_form()";>
<input type="text" name="fname"/><br>
<input type="text" name="sname"/><br>
languahe you know <br/>
<input type="checkbox" name="language[]" value="1" <?php if(in_array(1,$my_stored_language)){echo "checked";}?>><label>PHP</label><br>
<input type="checkbox" name="language[]" value="2" <?php if(in_array(2,$my_stored_language)){echo "checked";}?>><label>Java</label><br>
<input type="checkbox" name="language[]" value="3" <?php if(in_array(3,$my_stored_language)){echo "checked";}?>><label>c</label><br>
<input type="checkbox" name="language[]" value="4" <?php if(in_array(4,$my_stored_language)){echo "checked";}?>><label>javascript</label><br>
<input type="checkbox" name="language[]" value="5" <?php if(in_array(5,$my_stored_language)){echo "checked";}?>><label>c#</label><br>
<input type="checkbox" name="language[]" value="6" <?php if(in_array(6,$my_stored_language)){echo "checked";}?>><label>.net</label><br>
<input type="submit" name="submit" value="submit">
</form>
<script>
function validate_form()
{
valid = true;
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
return valid;
}
</script>

function validate_form()
{
valid = true;
$('form').find('input[type=checkbox]').each(function(){
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
)};
return valid;
}
Try this one.

Related

RadioButton Value doesn't insert into mySql DB whit Php

During a simple insertion query via PHP and MySQL, I find the following problem:
it does not insert all the values ​​of the radioButton .. actually actually only inserts one :(
I can not understand why !!
I think there is a problem with the $ _POST because by printing it I only get the value of the first radioButton jumping all the others ...
I am attaching screenshots to explain you better
enter image description here
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
$connessione = mysql_connect("$servername","$username","$password");
if(!$connessione)
{
die("Errore critico di Connessione al Database" . mysql_error());
}
//connessione
mysql_select_db("$dbname",$connessione);
$fkIDCantiere = $_GET["idCantiere"];
$idAffidataria = $_POST["idAffidataria"];
$nomeCantiere =$_POST["nomeCantiere"];
$addettoSicurezza=$_POST["addettoSicurezza"];
$mailAffidataria = $_POST["mailAffidataria"];
$scadenzaCCIAA = $_POST["scadenzaCCIAA"];
$scadenzaDURC = $_POST["scadenzaDURC"];
$contrattoDiAppalto = $_POST["contrattoDiAppalto"];
$pianoDiEmergenzaEAggiornamenti = $_POST["pianoDiEmergenzaEAggiornamenti"];
$CCIAA = $_POST["CCIAA"];
$DURC= $_POST["DURC"];
$DVR= $_POST["DVR"];
$dichiarazioneITP =$_POST["DichiarazioneITP"];
$posRevA = $_POST["posRevA"];
$posRevB = $_POST["posRevB"];
$posRevC = $_POST["posRevC"];
$posInt01 =$_POST["posInt01"];
$registroInfortuni = $_POST["registroInfortuni"];
$nominaRSPP = $_POST["nominaRSPP"];
$attestatoFormazioneRspp = $_POST["attestatoFormazioneRspp"];
$verbaleElezioneRLS = $_POST["verbaleElezioneRLS"];
$attestatoFormazioneRLS = $_POST["attestatoFormazioneRLS"];
$delegaDC = $_POST["DelegaDC"];
$formazioneDirigente = $_POST["formazioneDirigente"];
$nominaPreposto = $_POST["nominaPreposto"];
$formazionePreposto = $_POST["formazionePreposto"];
$nominaAddettoAntincendio =$_POST["nominaAddettoAntincendio"];
$formazioneAddettoAntincendio = $_POST["formazioneAddettoAntincendio"];
$nominaAddettoPS = $_POST["nominaAddettoPS"];
$formazioneAddettoPS = $_POST["formazioneAddettoPS"];
$schedeSicurezzaSostanzeChimiche = $_POST["schedeSicurezzaSostanzeChimiche"];
$nominaMedicoCompetente = $_POST["nominaMedicoCompetente"];
$impiantoElettricoComunicazioneInail = $_POST["impiantoElettricoComunicazioneInail"];
$derogaAlRumore = $_POST["derogaAlRumore"];
$note1 = $_POST["note1"];
$note2= $_POST["note2"];
$note3= $_POST["note3"];
$note4= $_POST["note4"];
$note5= $_POST["note5"];
$note6= $_POST["note6"];
$note7= $_POST["note7"];
$note8= $_POST["note8"];
$note9= $_POST["note9"];
$note10= $_POST["note10"];
$note11= $_POST["note11"];
$note12= $_POST["note12"];
$note13= $_POST["note13"];
$note14= $_POST["note14"];
$note15= $_POST["note15"];
$note16= $_POST["note16"];
$note17= $_POST["note17"];
$note18= $_POST["note18"];
$note19= $_POST["note19"];
$note20= $_POST["note20"];
$note21= $_POST["note21"];
$note22= $_POST["note22"];
$note23= $_POST["note23"];
$note24= $_POST["note24"];
$note25= $_POST["note25"];
$note26= $_POST["note26"];
$note27= $_POST["note27"];
$note28= $_POST["note28"];
$note29= $_POST["note29"];
$note30= $_POST["note30"];
$note31= $_POST["note31"];
print_r($_POST);
$ris_news = mysql_query("INSERT INTO Affidataria (idAffidataria,
nomeCantiere,
addettoSicurezza,
mailAffidataria,
scadenzaCCIAA,
scadenzaDURC,
fkIDCantiere,
contrattoDiAppalto,
pianoDiEmergenzaEAggiornamenti,
CCIAA,
DURC,
DVR,
DichiarazioneITP,
posRevA,
posRevB,
posRevC,
posInt01,
registroInfortuni,
nominaRSPP,
attestatoFormazioneRspp,
verbaleElezioneRLS,
attestatoFormazioneRLS,
DelegaDC,
formazioneDirigente,
nominaPreposto,
formazionePreposto,
nominaAddettoAntincendio,
formazioneAddettoAntincendio,
nominaAddettoPS,
formazioneAddettoPS,
schedeSicurezzaSostanzeChimiche,
nominaMedicoCompetente,
impiantoElettricoComunicazioneInail,
derogaAlRumore,
note1,
note2,
note3,
note4,
note5,
note6,
note7,
note8,
note9,
note10,
note11,
note12,
note13,
note14,
note15,
note16,
note17,
note18,
note19,
note20,
note21,
note22,
note23,
note24,
note25,
note26,
note27,
note28,
note29,
note30,
note31)
VALUES ('$idAffidataria',
'$nomeCantiere',
'$addettoSicurezza',
'$mailAffidataria',
'$scadenzaCCIAA',
'$scadenzaDURC',
'$fkIDCantiere',
'$contrattoDiAppalto',
'$pianoDiEmergenzaEAggiornamenti',
'$CCIAA',
'$DURC',
'$DVR',
'$dichiarazioneITP',
'$posRevA',
'$posRevB',
'$posRevC',
'$posInt01',
'$registroInfortuni',
'$nominaRSPP',
'$attestatoFormazioneRspp',
'$verbaleElezioneRLS',
'$attestatoFormazioneRLS',
'$delegaDC',
'$formazioneDirigente',
'$nominaPreposto',
'$formazionePreposto',
'$nominaAddettoAntincendio',
'$formazioneAddettoAntincendio',
'$nominaAddettoPS',
'$formazioneAddettoPS',
'$schedeSicurezzaSostanzeChimiche',
'$nominaMedicoCompetente',
'$impiantoElettricoComunicazioneInail',
'$derogaAlRumore',
'$note1',
'$note2',
'$note3',
'$note4',
'$note5',
'$note6',
'$note7',
'$note8',
'$note9',
'$note10',
'$note11',
'$note12',
'$note13',
'$note14',
'$note15',
'$note16',
'$note17',
'$note18',
'$note19',
'$note20',
'$note21',
'$note22',
'$note23',
'$note24',
'$note25',
'$note26',
'$note27',
'$note28',
'$note29',
'$note30',
'$note31')");
if (!$ris_news) {
//messaggio di errore per capire il problema
exit ('<p> Errore mentre recuperavo i dati ' . mysql_error() . ' </p>');
}
/*try
{
$toInsert1 ="INSERT INTO Affidataria (idAffidataria,nomeAffidataria,addettoSicurezza,mailAffidataria,scadenzaCCIAA,scadenzaDURC) VALUES ('$nomeAffidataria','$addettoSicurezza','$mailAffidataria','$scadenzaCCIAA','$scadenzaDURC')";
$result1 = mysql_query($toInsert1);
}
catch(Exception $var)
{
print $var->getMessage();
}
*/
?>
<html>
<body>
<script language="javascript">
function controlla(){
x=document.prova;
if (x.scelta.value=="si"){
window.location.href = '../subAffidatario.php?idAffidataria=<?php echo $idAffidataria?>'
return false;
}
if (x.scelta.value=="no"){
alert("Hai risposto no");
window.location.href = '../affidatario.php'
return false;
}
}
</script>
<fieldset>
<strong>Sei sicuro di voler continuare?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br />
NO<input type="radio" name="scelta" value="no" /><br />
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>
this is the result that returns the query by inserting "print_r ($ _ POST);"
enter image description here
practically reads the first radioButton "$contrattoDiAppalto" and sends me an error on the next radioButton called (as seen by the error)
"PianoDiEmergenzaEAggiornamenti"
I also show you the html code I used for radio buttons
<html>
<body>
<table>
<tr>
<td bgcolor="#B35556"><form method="POST">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="1" onchange="color(this)" /> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="0" onchange="color(this)" checked/>
</form></td></tr>
<tr>
<td bgcolor="#B35556">
<form method="POST">
OK <input type="radio" name="pianoDiEmergenzaEAggiornamenti" id="pianoDiEmergenzaEAggiornamenti" value="1" onchange="color(this)" /> <BR>
NO <input type="radio" name="pianoDiEmergenzaEAggiornamenti" id="pianoDiEmergenzaEAggiornamenti" value="0" onchange="color(this)" checked/>
</form>
</td></tr>
</table>
</body>
</html>
Moral of all this: HOW DID YOU READ ONLY THE FIRST RADIOBUTTON AVOIDING ALL OTHERS?
In your html code you use several tags. This results in submitting one of the forms will not send the contend of the other forms. So you just have to remove the form closing and opening again to make it work.
<html>
<body>
<table>
<tr>
<td bgcolor="#B35556"><form method="POST">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="1" onchange="color(this)" /> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="0" onchange="color(this)" checked/>
</td></tr>
<tr>
<td bgcolor="#B35556">
OK <input type="radio" name="pianoDiEmergenzaEAggiornamenti" id="pianoDiEmergenzaEAggiornamenti" value="1" onchange="color(this)" /> <BR>
NO <input type="radio" name="pianoDiEmergenzaEAggiornamenti" id="pianoDiEmergenzaEAggiornamenti" value="0" onchange="color(this)" checked/>
</form>
</td></tr>
</table>
</body>
</html>
But please dive deeper into html and js, as there are other "errors" too. So for example you use the same id on two html elements wich is not correct. "document.getElementById()" only will return a random one (usually the first), but that is not as it is supposed to be. I would suggest to remove the id's as long as you do not use them in your java script code.

Save and load checkboxes state to file

I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>

Can not limit the number of check boxes to be selected

I'm using foreach loop to generate the checkboxes in my form. It is given below.
<?php $index = 0;
foreach($cameramen as $n_key){ ?>
<div class="checkbox">
<label>
<input type="checkbox" id="cameramen_<?php echo $index+1; ?>" name="cameramen" class="subscriber" value="<?php echo $index+1; ?>">
<?php
echo $n_key->emplist3;
$index++;
?>
</label>
</div>
<br/><br/>
<?php } ?>
I want to limit the number of checkboxes to be selected by the user to two.
I used the following javascript function but it not worked(It allows to select all the checkboxes).
$("input[name=cameramen]").change(function(){
var max= 2;
console.log($("input[name=cameramen]:checked").length);
if( $("input[name=cameramen]:checked").length == max ){
$("input[name=cameramen]").attr('disabled', 'true');
$("input[name=cameramen]:checked").removeAttr('disabled');
}else{
$("input[name=cameramen]").removeAttr('disabled');
}
});
Someone please help me to solve this problem which I have being struggling for hours to solve.
You can try this:
$(document).ready(function(){
$(".cb").on('click', function(e) {
var count = 0;
var list = $('.cb');
$('.cb').each(function(i) {
if($(this).is(':checked')) {
count++;
}
});
if(count > 2)
{
alert('You cannot check more than 2 checkboxes!');
$(this).prop('checked', false);
//return false;
} else {
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="cb" type="checkbox">Checkbox 1
<br />
<input class="cb" type="checkbox">Checkbox 2
<br />
<input class="cb" type="checkbox">Checkbox 3
<br />
<input class="cb" type="checkbox">Checkbox 4
</div>
Hope this helps!

Validation on other when more than one checkbox is checked

I have a form that has series of checkboxes. When the other checkbox is selected an alert appears if you don't fill in the other textbox.
If I select more than one checkbox it doesn't validate at all?
<form>
<div id="form-2" class="pages active" data-page="form-2" style="display: block;">
<p>Please indicate below the quality issue(s) you were not happy with. Pick as many options as apply. <span class="required">*</span></p>
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="Other, please specify in the box below">
<input type="text" name="qual-form-other-form-2" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false">
<button class="next-page" data-page-id="form-2">Next</button>
</div>
</form>
<script>
if (pageCurrent.data('page') == 'form-2') {
var answer = pageCurrent.find('input[name="qual-form-2[]"]:checked').val();
if ( (answer == 'Other, please specify in the box below') && ($('input[name="qual-form-other-form-2"]').val().length > 0)) {
$('input[name="qual-form-other-form-2"]').removeClass('empty');
return true;
} else if ( (answer == 'Other, please specify in the box below') && (!$('input[name="qual-form-other-form-2"]').val().length > 0)) {
alert('Please specify other');
$('input[name="qual-form-other-form-2"]').addClass('empty');
return false;
} else if ( (answer == 'Other, please specify in the box below') && (!$('input[name="qual-form-other-form-2"]').val().length > 0) && ($('input[name="qual-form-2[]').is(":checked"))) {
alert('Please specify other');
$('input[name="qual-form-other-form-2"]').addClass('empty');
return false;
} else if ($('input[name="qual-form-2[]').is(":checked")) {
return true;
} else {
alert('Validation errors occurred. Please confirm the fields and submit it again.');
}
}
</script>
Try this : change your button type="button" and call below script.
$(function(){
$('.next-page').click(function(){
var checkCount = $('input[name="qual-form-2[]"]:checked').length;
//check atleast one checkbox checked
if(checkCount > 0)
{
var checkOther = $('input[name="qual-form-2[]"]:last');
var checkNotOther = $('input[name="qual-form-2[]"]:checked').not(checkOther);
//if 'other' and any of the rest is checked show alert
if(checkNotOther.length > 0 && checkOther.is(':checked'))
{
$('input[name="qual-form-other-form-2"]').addClass('empty');
alert('Please select either "Other" or another checkbox');
}
//if other checked and input is empty show alert
else if(checkOther.is(':checked') && $('input[name="qual-form-other-form-2"]').val() == "")
{
$('input[name="qual-form-other-form-2"]').addClass('empty');
alert('Please specify other');
}
else
{
alert('Validation Succeeded');
}
}
else
{
alert('Please check atleast one checkbox');
}
});
});
JSFiddle Demo

JavaScript checkbox submit only one input

I have problem on the checkbox submission. The code is as below:
JavaScript
function init () {
document.getElementById("pizza").topping[0].checked=true;
document.getElementById("btn").onclick=poll;
}
onload = init;
function poll () {
var i, isOK, summary="";
var form=document.getElementById("pizza");
for (i=0; i < form.topping.length; i++) {
if (form.topping[i].checked) {
summary+=form.topping[i].value+" ";
}
}
isOK = confirm("Submit these choices?\n" + summary);
if (isOK) {
form.submit();
} else {
return false;
}
}
HTML
<form id="pizza" action="poll.php" method="POST">
<div id="panel">Pizza Topping?
<input type="checkbox" name="topping" value="Cheese">Cheese</input>
<input type="checkbox" name="topping" value="Ham">Ham</input>
<input type="checkbox" name="topping" value="Peppers">Peppers</input>
<input id="btn" type="button" value="Confirm Choices"></input>
</div>
</form>
poll.php
<?php
echo "<br>***************<br>";
var_dump($_POST);
echo '*********************';
?>
The JS confirm message:
Submit these choices?
Cheese Peppers
The output of poll.php:
array (size=1)
'topping' => string 'Peppers' (length=7)
So my problem is: I checked Cheese and Peppers but I only got Peppers submitted. Can anyone help me?
Give an array like name(with the suffix []) to the input elements
<input type="checkbox" name="topping[]" value="Cheese">Cheese</input>
<input type="checkbox" name="topping[]" value="Ham">Ham</input>
<input type="checkbox" name="topping[]" value="Peppers">Peppers</input>

Categories