Debugging PHP Form Handling, with Dynamic HTML Fields - javascript

I'm using this HTML code to allow the user to add more fields and remove them from this order form.
<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Form Processing with PHP | Tech Stream</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 20){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum Photos per order is 20.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all Picture fields.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form action="process.php" class="register" method="POST">
<fieldset class="row1">
<legend>Order Details</legend>
<p>
<input type="button" value="Add Picture" onClick="addRow('dataTable')" />
<input type="button" value="Remove Picture" onClick="deleteRow('dataTable')" />
<p>(All acions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="dataTable" class="form" border="1"> <!-- These Fields get duplicated -->
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" checked="" /></td>
<td>
<label for="BX_file">Filename</label>
<input type="text" required="required" class="small" name="BX_file[]">
</td>
<td>
<label for="BX_gallery">Gallery</label>
<select id="BX_gallery" name="BX_gallery" required="required">
<option>....</option>
<option>Nature</option>
<option>Stilllife</option>
<option>Portrait</option>
<option>Constructed</option>
<option>Nature</option>
<option>Black & White </option>
<option>Rotarian Dinner Dance 25/04/2015</option>
</select>
</td>
<td>
<label for="BX_medium">Medium</label>
<select id="BX_medium" name="BX_medium" required="required">
<option>....</option>
<option>Small Print</option>
<option>Medium Print</option>
<option>Large Print</option>
<option>Custom Print</option>
<option>CD Image Disc</option>
<option>Digital Download</option>
</select>
</td>
<td>
<label for="BX_quantity">Quantity</label>
<input type="number" required="required" class="small" name="BX_quantity[]">
</td>
</p>
</tr>
</tbody>
</table> <!-- End of Fields that are duplicated. -->
<fieldset class="row2">
<legend>Terms and Mailing</legend>
<p class="agreement">
<input type="checkbox" value=""/>
<label>* I accept the Terms and Conditions</label>
</p>
<div class="clear"></div>
</fieldset>
<fieldset class="row3">
<legend>Other</legend>
<p class="notes">
<input type="text">
<label>Additional Notes</label>
</p>
<div class="clear"></div>
</fieldset>
<input class="submit" type="submit" value="Confirm »" />
<div class="clear"></div>
</fieldset>
</form>
</body>
</html>
I'm now trying to handle the field inputs via PHP so they can be sent via email to me. However I can't seem to get it working. Could anyone point out where my PHP code is going wrong?
<?php
$str_File = $_POST['BX_FILE'];
$str_Gall = $_POST['BX_GALLERY'];
$str_Med = $_POST['BX_MEDIUM'];
$int_Quant = $_POST['BX_QUANT'];
$str_Notes = $_POST['NOTES'];
//Gets all the values and saves them to the variables in array format.
$int_Num = count($FILE) //Gets the size of th array.
for ($x = 1; $x <= $int_Num; $x++) {
$str_ORD = "Order Field: $x, Filename: $str_File[$x], Gallery: $str_Gall[$x], Photo Medium: $str_Med[$x], Quantity: $int_Quant[$x]"
}
//Loops through all the arrays assembling the message for the email.
mail("harrysanderson#live.co.uk","Order Test",$str_ORD)
//Sends email.
This is the tutorial I've been following:
Any help is greatly appreciated!
Sorry I'm a beginner when it comes to PHP.

Key values in post array are case sensitive. Use the same names in POST which you have used in your input elements.
For example,
<input type="text" required="required" class="small" name="BX_file[]">
Here, POST should be $_POST['BX_file']

There are some issues with your code:
Your field names are the same. BX_file[] won't turn into an array (if that's what's intended) just because you put brackets at the end of it. You need to manage input names dynamically via JS, or else your fields will mutually overwrite each other at POST event.
See the example:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="post" action="test5.php">
<input type="text" name="input_foo">
<input type="text" name="input_bar">
<input type="text" name="input_foo">
<input type="submit" value="post">
</form>
</body>
</html>
Actioin file:
<?php
print_r($_POST);
Outputs:
Array ( [input_foo] => test3 [input_bar] => test2 )

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

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.

How to fill div with values from form?

I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);

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;
}

form display results under questions + array?

I am having trouble displaying the results on my form under the questions. I thought I had it right. Also I need to create an Array that will hold the answers, which it will randomly pick one, doesnt have to go by the answers. I can't figure out how to display the results on the same page (I have looked and had no luck) Could anyone help me
<!doctype html>
<html>
<?php
include "menu.html"
?>
<head>
<meta charset="UTF-8">
<title>Form</title>
<link href="styles.css" rel="stylesheet">
<script>
function checkForm(){
var chk = true;
var Name = document.getElementById("txt");
var methd= document.getElementById("method");
var rad1= document.getElementById("radM");
var sel= document.getElementById("selM");
var necro = document.getElementById("a");
var guard = document.getElementById("b");
var ele = document.getElementById("c");
var shatter = document.getElementById("imp");
var cor = 0;
Name.style.backgroundColor="#fff";
methd.setAttribute("style", "display:none");
rad1.setAttribute("style", "display:none");
sel.setAttribute("style", "display:none");
if (Name.value==''){
Name.style.backgroundColor = "red";
methd.setAttribute("style", "display:inline");
chk = false;
}
if ((necro.checked==false) && (guard.checked==false) && (ele.checked==false)){
rad1.setAttribute("style", "display:inline");
}
if (shatter.value==0){
selM.setAttribute("style", "display:inline");
}
if (chk==false){
document.getElementById("error").setAttribute("style", "display:inline");
} else {
if (Name.value=="no"){
document.getElementById(txt).innerHTML += 'No';}
if (Name.value=="yes"){
document.getElementById(txt).innerHTML += 'Yes';}
if (ele.checked == true){
document.getElementById(c).innerHTML += 'Elementalist';}
if (necro.checked == true){
document.getElementById(a) += 'Necromancer';}
if (guard.checked == true){
document.getElementById(b) +='Guardian';}
if (shatter.value==1){
document.getElementById(imp) += 'Shatter';
}
if (shatter.value==2){
document.getElementById(imp) += 'Sunless';
}
if (shatter.value==3){
document.getElementById(imp) += 'Claw';
}
style.display = "inline";
innerHTML = "<span>You chose " + imp + txt + " correct!</span>";
}
}
</script>
</head>
<body>
<div class="page">
<article>
<div id="error" class="error"></div>
<h1>What Guild Wars 2 Profession Are You</h1>
<div class="cssTable" style="margin-top:-25px;">
<form method="post" action="thankyou.php" >
<table>
<tr><td colspan="3"></td></tr>
<tr>
<td><div align="right">In Guild Wars 2 Do You Like To Do Damage? </div> </td><td width="217"><input id="txt" name="txt" type="text" size="25"> <br/></td><td><div id="method" style="display:none"><img height="25px" src="purple.png" ></div></td><br/></tr>
<tr>
<td><div align="right">What Best Describes You?</div></td><td>
<input id="a" type="radio" name = "group1" value="A">Healer</input><br/>
<input id="b" type="radio" name = "group1" value="B">One With The Elements</input><br/>
<input id="c" type="radio" name = "group1" value="C">Darkness</input>
</td><td><div id="radM" style="display:none"><img height="25px" src="purple.png"></div></td>
</tr>
<tr>
<td>What One Skill Would You Like To Have?</td>
<td>
<select id="imp"><option value="0" selected="true">Pick A Skill</option>
<option value="1">Stealth</option>
<option value="2">Summon Illusions</option>
<option value="3">Great With A Bow and Arrow</option></select>
</td><td><div id="selM" style="display:none"><img height="25px" src="purple.png"></div></td>
</tr>
<tr><td colspan="3" align="right"><input type="button" class="styled-button-7" value="Send" onclick="checkForm()" /><span id="grde" style="padding-left:25px"> </span></td></tr></table></form></div></article>
</main></div>
</body>
</html>
I moved your call to checkForm() from an onclick on a button to the onsubmit of the form, and started returning chk from checkForm(). You should go through your checkForm() function and start making it work field by field. There are properties that you're trying to access incorrectly.
You can see it at:
http://jsbin.com/homeq/1/

Categories