JavaScript checkbox submit only one input - javascript

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>

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.

Different groups of checkbox not working in jquery

I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.
<body>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee<br>
<input type="submit" id="__mainAnimals" />
<br><br><br><br><br><br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
<input type="checkbox" value="Tea" name="drinks" />Tea<br>
<input type="checkbox" value="Milk" name="drinks" />Milk<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
<input type="submit" id="__mainDrinks" />
</div>
<div id="__DIVresult"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#__mainAnimals').click(function () {
getSelectedCheckBoxes('animals');
});
$('#__mainDrinks').click(function () {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function (groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('__DIVresult').html(resultString);
}
else {
$('__DIVresult').html("No checkbox checked");
}
};
});
</script>
</body>
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')
2nd An ID should start with a letter for compatibility
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
3rd some small update, added two result div, one for animal one for drink:
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
Then target them dynamically with $('#DIVresult'+groupName).html(resultString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion
<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger
<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant
<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee
<br>
<input type="submit" id="mainAnimals" />
<br>
<br>
<br>
<br>
<br>
<br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe
<br>
<input type="checkbox" value="Tea" name="drinks" />Tea
<br>
<input type="checkbox" value="Milk" name="drinks" />Milk
<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha
<br>
<input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#mainAnimals').click(function() {
getSelectedCheckBoxes('animals');
});
$('#mainDrinks').click(function() {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function(groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function() {
resultString += $(this).val() + "<br/>";
});
$('#DIVresult'+groupName).html(resultString);
} else {
$('#DIVresult'+groupName).html("No checkbox checked");
}
};
});
</script>
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.
<html>
<form>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion" />Lion</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>
<input type="button" id="save_value" name="save_value" value="Save" /></br>
<textarea id="t"></textarea>
</form>
<script>
function updateTextArea() {
var allVals = [];
$('.ads_Checkbox:checked').each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals);
}
$('#save_value').click(function(){
$('.ads_Checkbox:checked').each(function(){
updateTextArea();
});
});
Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.

Launch script after confirming action (HTML)

So, I'm currently doing my final internship for the Network Administration training at school. And I've been asked to create a simple web page that allows for selecting a range of servers to perform a clean install on. Like: when I select 'Server 1' and 'Server 4' > click 'Submit' > confirm my action > launch VBscript that performs clean install.
What I have so far (also refer to pieces of code at end):
- Basic welcome text
- Check boxes
- Select all (javascript)
- Continue button
- When clicking continue button > show warning that asks for confirmation
What I want it to do, is launching the script of the selected box(es) after confirming. Is that possible? I mean, I assume I'll need something else than HTML. Javascript maybe? How would I do such thing?
I'm not a total expert with this stuff, not at all. I do have some experience with HTML and CSS, but Javascript and all that? Nope, not at all. Would be very happy to have some help with this!
<html>
<head>
<title>
Huawei Cleaning Center
</title>
<script type="text/javascript">
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
</script>
<script type="text/javascript">
function clicked() {
if (confirm('Weet u zeker dat u wilt doorgaan?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
</head>
<body>
<center><h1>Welkom bij Huawei Cleaning Center!</h1></center>
<br><br>
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:<br><br>
<form method="GET" action="page17.php" name="myForm" onsubmit="return false;">
<label for="myCheckbox1">
<input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1">
172.16.115.11 </label>
<br>
<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2">
172.16.115.21 </label>
<br>
<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3">
172.16.115.31 </label>
<br>
<label for="myCheckbox4"><input type="checkbox" name="myCheckbox" value="4" id="myCheckbox4">
172.16.115.41 </label>
<br><br><input type="submit" id="submit1" onclick="clicked();" value="Doorgaan">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="Selecteer alles">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="Deselecteer alles">
</form>
</body>
</html>
Change your js like this. Form gonna submit if you click yes
<script type="text/javascript">
function clicked() {
var confirmed = confirm('Weet u zeker dat u wilt doorgaan?')
if (confirmed) {
yourformelement.submit();
} else {
alert('You clicked No');
}
}
</script>
if you use JQuery you also could do this:
$(yourformelement).submit(function(e){
var dialogresult = confirm('Confirm');
if (dialogresult ) {
return true;
} else {
return false;
}
});
Looking at your code, it seems like you're using PHP. In this case you could try something like this in your php page (page17.php as referred in the action attribute):
if(!empty($_POST['serverList'])) {
foreach($_POST['serverList'] as $arg) {
exec('cscript "path/to/script.vbs" ' . $arg);
}
}
$_POST['serverList'] contains an array of the checkboxes values and the foraech loop will execute a VBscript passing the values as arguments.
Here's a snippet of the JS/CSS/HTML code:
function setCheckboxes(checkboxName, value) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = value;
}
}
function submitForm(checkboxName) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == true) {
confirmation = confirm('Weet u zeker dat u wilt doorgaan?');
if (confirmation) {
return true;
} else {
return false;
}
}
}
alert('No server selected!');
return false;
}
.main-heading {
margin-bottom: 60px;
text-align: center;
}
.info {
margin-bottom: 60px;
}
<h1 class="main-heading">Welkom bij Huawei Cleaning Center!</h1>
<p class="info">
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:
</p>
<form method="POST" action="page17.php" name="myForm" onsubmit="return false;">
<label for="checkbox-1">
<input type="checkbox" name="serverList[]" value="1" id="checkbox-1">
172.16.115.11
</label>
<br>
<label for="checkbox-2">
<input type="checkbox" name="serverList[]" value="2" id="checkbox-2">
172.16.115.21
</label>
<br>
<label for="checkbox-3">
<input type="checkbox" name="serverList[]" value="3" id="checkbox-3">
172.16.115.31
</label>
<br>
<label for="checkbox-4">
<input type="checkbox" name="serverList[]" value="4" id="checkbox-4">
172.16.115.41
</label>
<br><br>
<input type="submit" onclick="submitForm('serverList[]');" value="Doorgaan">
<input type="button" onclick="setCheckboxes('serverList[]', true);" value="Selecteer alles">
<input type="reset" value="Deselecteer alles">
</form>
Hope it helps :)

jQuery validation to select at least one checkbox

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.

how to validate my form field after my check box is checked?

i have created one form with dynamically created fields. and i have a one check box with unique ID . when user clicks that check box then only those two fields are visible ("name and age"). after clicking only "age" field need to be validate .
here is my code :
$(document).ready(function() {
$('#person').click(function() {
function formValidator(){
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
});
});
$(document).ready(function() {
$('#person').click(function() {
$('#name').attr('required','required');
$('#age').attr('required','required');
});
});
style is :
.selectContainer{
display:none;
}
input[type=checkbox]:checked ~ .selectContainer {
display:block;
}
Html code is:
<form action="" method="post" onSubmit="return formValidator()">
<label for="name">Any Accompanying Person ?:</label>
<input type="checkbox" name="person" id="person" >Yes
<div class="selectContainer">
<br>
<label>Person Details</label>
<p>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</div>
<h3>Choose Your Payment Option</h3>
<h1>
<div style="padding-left:150px;">
<input type="radio" name="type" value="visa">VISA/MASTER CARD:<br />
<input type="radio" name="type" value="cheque"> CHEQUE/DEMAND DRAFT<br />
<input type="radio" name="type" value="neft">NEFT<br /><br/>
</div>
<label></label>
<input type="submit" name="submit" value="submit"><br />
</form>
problem: the form field "age" is validating successfully by clicking check box ("Any Accompanying Person ?:"). problem is when user try to submit the form without clicking that check box then all so its asking for validate . how get salutation for this ? please help
The validator is within a click handler, which should live outside of that (On the base on the document.ready()).
Also if you just want to validate when that checkbox is clicked you could check it within the javascript and select it via the name of the checkbox (If it has a unique ID each time).
function formValidator(){
var age = document.getElementsByName('age[]');
if($("input[name = 'chk[]']").prop('checked')){
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
Bring all javascript functions outside of click events. Try this formValidator function
function formValidator(){
if($("#person").is(":checked")) {
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}

Categories