add value to total if radio box checked - javascript

There is something not working at this script.
I need when check one radio button to add the amount at the total price.
This is doing well, but if I check different radio buttons, it ads all of them.
If I have total = 100$; and button1=10$, button2=10$, button3=10$
and if I check all 3... I will get total = 130$ instead of 110$
function calculateTotal(payment)
{
var check=document.getElementById("check").value;
var city = document.getElementsByName('loc');
var value= payment.value;
var total= document.getElementById("totl").value;
var tcharge;
var pvcharge=document.getElementById("ch").value;
if(value==0 && check==0)
return;
if(value==0 && check==1)
{
total= parseFloat(parseFloat(total)-parseFloat(pvcharge)).toFixed(2);
tcharge=0;
}else
{
if(total>=200)
return;
if(value=='online' || value =='transfer_bancar' || value=='cash' || value == 'la_sediul_nostru')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+15.0).toFixed(2);
tcharge=15.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
}
else
if(value='la_expeditor')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+60.0).toFixed(2);
tcharge=60.00;
}
}
}
document.getElementById("tot").innerHTML=total+" LEI";
document.getElementById("totl").value=total;
document.getElementById("amt").value=total;
document.getElementById("tcharge").innerHTML=tcharge+" LEI";
document.getElementById("check").value=1;
document.getElementById("ch").value=tcharge;
}
radio box
<tr>
<td colspan="2"> <input type="radio" name="payment" value="online" id="online" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="transfer_bancar" id="bancar" onClick="calculateTotal(this); return bancarval();" /> <span class="fontext"><b>asdadadadasd</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="cash" onClick="calculateTotal(this);return empty();" /> <span class="fontext"><b>asdadadadadad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_expeditor" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdadad</span></td> </tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_sediul_nostru" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="0" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdasdasd</b></span></td> </tr>
<tr>
<td><span class="fontext"><b>Cost transport: </b></span></td> <td><span class="fontext" ><b id="tcharge">0.00 LEI</b></span></td> </tr>
and php
if($Tott<200)
if(isset($_POST['loc']))
{
$tcharges=$_POST['loc'];
if(isset($_POST['payment']))
{
$payment=$_POST['payment'];
if($payment!=0)
if($payment=='online' || $payment =='transfer_bancar' || $payment=='cash' || $payment == 'la_sediul_nostru')
{
if($tcharges=='in')
$Tott+=15;
else
$Tott+=30;
}else
if($payment=='la_expeditor')
{
if($tcharges=='in')
$Tott+=30;
else
$Tott+=60;
}
}
}

Each time, you're operating off the total of the previous calculation.
Offending line:
var total= document.getElementById("totl").value;
Instead, change it to operate off the original, clean value.

Related

Use JavaScript to get value of the for each

I'm new using JavaScript. I need to get the value ${prdcts.precioUnidad} of the checked line. The idea is to set the total price in a dynamic way, so when the user checks or unchecks each line the value of total either adds the new value when checked, or subtracts the previous value when unchecked.
I tried to get the value using the getElement() methods, but I don't know how to access the value of the variable within that specific row.
This is the HTML:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ventas</title>
</head>
<body>
<center><h1>Venta de Productos</h1>
<form action="venta.htm" method="post">
<table id="tableID" border="4">
<tbody><tr>
<th>ID</th>
<th>Nombre</th>
<th>Valor</th>
<th>Comprado</th>
</tr>
<tr>
<td>2</td>
<td>Chupetin</td>
<td>5.0</td>
<td><input name="check" type="checkbox" value="2" label="2" path="prdcts"></td>
</tr>
<tr>
<td>3</td>
<td>Alfajor DDL</td>
<td>30.0</td>
<td><input name="check" type="checkbox" value="3" label="3" path="prdcts"></td>
</tr>
<tr>
<td>4</td>
<td>Sanguche Mila</td>
<td>60.0</td>
<td><input name="check" type="checkbox" value="4" label="4" path="prdcts"></td>
</tr>
</tbody></table>
<br>
<br>
<br>
<table border="4">
<tbody><tr>
<td>Total Compra: <input name="total" id="total" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td>Monto Pagado: <input name="monto" id="monto" type="number" value="0"></td>
</tr>
<tr>
<td>Vuelto: <input name="vuelto" id="vuelto" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td><input name="begin" onclick="calcularVuelto()" type="button" value="Calcular Vuelto"></td>
</tr>
</tbody></table>
<br>
<br>
<input name="clear" onclick="window.location.href = 'venta.htm'" type="button" value="Borrar venta">
<input name="begin" onclick="window.location.href = 'principal.htm'" type="button" value="Inicio">
<input name="confirm" type="submit" value="Confirmar Venta">
<br>
</form>
</center>
<script>
// Make it an Array with "Array.from" so we can use reduce() on it
var $$checkboxes = Array.from(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
alert("aca");
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
alert("aca2")
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
function calcularVuelto() {
var total = document.getElementById("total").value;
var pago = document.getElementById("monto").value;
var fTotal = parseFloat(total);
var fPago = parseFloat(pago);
totalResta = fPago - fTotal;
document.getElementById("vuelto").value = totalResta;
}
</script>
</body></html>
You can use Array.prototype.reduce() to calculate the total:
// Make it an Array with "[].slice.call" so we can use reduce() on it
var $$checkboxes = [].slice.call(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
<table border="4">
<tr><th>ID</th> <th>Nombre</th> <th>Valor</th> <th>Comprado</th> </tr>
<tr><td>x</td><td>X</td><td>5.99</td><td><input name="check" type="checkbox" value="x" label="X"/></td></tr>
<tr><td>y</td><td>Y</td><td>3.95</td><td><input name="check" type="checkbox" value="y" label="Y"/></td></tr>
<tr><td>z</td><td>Z</td><td>14.20</td><td><input name="check" type="checkbox" value="z" label="Z"/></td></tr>
</table>
<p>Total Compra: <input name="total" id="total" type="number" value="0" readonly/></p>
The checked flag is either on or off. It doesn't take an argument. So it looks like
<input type="checkbox" name="name" checked> checked </input>
<br/>
<input type="checkbox" name="name"> unchecked</input>
In your code you'll need something like: ${prdcts.idProducto ? "checked" : ""}

Need help getting fields to Populate using Javascript

I am taking an introduction course to HTML and have been struggling to find my error with a page that uses java. I am sure I am making a simple mistake but I am not seeing it
Here is the fiddle of the code I am working with:
https://jsfiddle.net/Terranova1340/ctc66nmu/2/
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAcces1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAcces2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAcces3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
Java is
function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
My issue is the Base Price to Estimated Total Price fields aren't populating.
Thanks in advance!
function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
You are using wrong id's, change to optAccess1,optAccess2,optAccess3 here
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>

Javascript submit function returns Object is not a function error

Am using this function for the form submission just after one last check of 2 fields. But when submitting the form using javascript it returns the Object is not a function error. Didnt pasted the entire code of this page. pasted the required fields for this function. Any helps appreciated
<script type="text/javascript">
function validamt(strval){
var letters = /^[0-9]+(\.[0-9]{1,2})?$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function validno(strval){
var letters = /^\d+$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function finalcheck(){
var discount=$("#discount").val();
var stax=$("#stax").val();
var err=0;
if(discount!="In Rupees only" || stax!="(%)"){
if(!validno(stax)){err=1; alert('Invalid Service Tax');$("#stax").focus();}
if(!validamt(discount)){err=1;alert('Invalid Discount Amount');$("#discount").focus();}
}
alert(err);
if(err==0){
try{
document.getElementById('billsetupprocess').action="storebilling.php";
document.getElementById('billsetupprocess').submit();
}
catch(e){
alert(e);
}
}
}
</script>
<form name="billsetupprocess" id="billsetupprocess" method="post" action="storebilling.php" enctype="multipart/form-data" >
<table>
<tr>
<td>Discount</td>
<td><input name="discount" type="text" class="txtclass" id="discount" value="<?php if($discount!=""){echo $discount;} else {echo("In Rupees only");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='In Rupees only'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='In Rupees only';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/></td>
<td></td>
<td> </td>
</tr>
<tr>
<td>servicetax</td>
<td><input name="stax" type="text" class="txtclass" id="stax" value="<?php if($discount!=""){echo $servicetax;}else {echo("(%)");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='(%)'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='(%)';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/>
</td>
<td></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" id="submit" type="button" value="Save Setup" onclick="finalcheck()" class="btnclass" /></td>
<td> </td>
<td> </td>
</tr>
</table>

JavaScript checking & adding text to a table dynamically on submit button click

Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David

Javascript form (with radio buttons) validation not working

This code was working earlier today, then randomly stopped, something must of changed, but I can't work out what - please see below:
**UPDATE - code update below. Now it correctly recognises if a radio button is checked or not, however if a user tries to resubmit the form after an alert is displayed, the recognised state fails to update. Is a loop of some kind needed?
function checkForm()
{
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if (document.getElementById("questionone").checked==false)
{
alert("Question one must be completed");
return false;
}
if (document.getElementById("questiontwo").checked==false)
{
alert("Question two must be completed");
return false;
}
if (document.getElementById("questionthree").checked==false)
{
alert("Question three must be completed");
return false;
}
if (document.getElementById("questionfour").checked==false)
{
alert("Question four must be completed");
return false;
}
}
Example of the form's first question:
<tr>
<td class="question" colspan="4"><p class="question">Usain Bolt is the current world record holder for the men's 100 meters, but what is his best time?</p></td>
</tr>
<tr>
<td class="answer">8.45 seconds<input type="radio" value="Aone" name="Qone" id="questionone"></td>
<td class="answer">9.58 seconds<input type="radio" value="Atwo" name="Qone" id="questionone"></td>
<td class="answer">10.12 seconds<input type="radio" value="Athree" name="Qone" id="questionone"></td>
<td class="answer">9.32<input type="radio" value="Afour" name="Qone" id="question one">
</td>
</tr>
*****UPDATE new code below:************
<link rel="stylesheet" href="style.css" type="text/css">
<!-- inclusion of fb config -->
<?php require_once('config.php'); ?>
<!-- client side validation for text fields -->
<script language="JavaScript" type="text/javascript">
function checkForm()
{
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
/* HERE */
function isAnswered(name) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((input.name === name) && (input.checked)) {
return true;
}
}
return false;
}
if (!isAnswered("Qone")) {
alert("Question one must be completed");
return false;
}
if (!isAnswered("Qtwo")) {
alert("Question two must be completed");
return false;
}
if (!isAnswered("Qthree")) {
alert("Question three must be completed");
return false;
}
if (!isAnswered("Qfour")) {
alert("Question four must be completed");
return false;
}
}
</script>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sdfbcomp", $con);
// some code
?>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$Qone = $_POST["Qone"];
$Qtwo = $_POST["Qtwo"];
$Qthree = $_POST["Qthree"];
$Qfour = $_POST["Qfour"];
?>
</head>
<body>
<div id="tablediv">
<table id="comptable">
<form name="sdcomp" method="post" action="insert.php" onSubmit="return checkForm();">
<tr class="userdetailfields">
<p>Name:</p><input type="text" size="12" maxlength="12" name="name"></br>
</tr>
<tr class="userdetailfields">
<p>Email:</p><input type="text" size="12" maxlength="30" name="email"></br>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Usain Bolt is the current world record holder for the men's 100 meters, but what is his best time?</p></td>
</tr>
<tr>
<td class="answer">8.45 seconds<input type="radio" value="Aone" name="Qone" id="questionone"></td>
<td class="answer">9.58 seconds<input type="radio" value="Atwo" name="Qone" id="questionone"></td>
<td class="answer">10.12 seconds<input type="radio" value="Athree" name="Qone" id="questionone"></td>
<td class="answer">9.32<input type="radio" value="Afour" name="Qone" id="question one"> </td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question two:</p></td>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Bone" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer two<input type="radio" value="Btwo" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer three<input type="radio" value="Bthree" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer four<input type="radio" value="Bfour" name="Qtwo" id="questiontwo"></td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question three:</td></p>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Cone" name="Qthree" id="questionthree"></td>
<td class="answer">Answer two<input type="radio" value="Ctwo" name="Qthree" id="questionthree"></td>
<td class="answer">Answer three<input type="radio" value="Cthree" name="Qthree" id="questionthree"></td>
<td class="answer">Answer four<input type="radio" value="Cfour" name="Qthree" id="questionthree"></td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question four:</td></p>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Done" name="Qfour" id="questionfour"></td>
<td class="answer">Answer two<input type="radio" value="Dtwo" name="Qfour" id="questionfour"></td>
<td class="answer">Answer three<input type="radio" value="Dthree" name="Qfour" id="questionfour"></td>
<td class="answer">Answer four<input type="radio" value="Dfour" name="Qfour" id="questionfour"></td>
</tr>
<tr><td><input type="submit" value="submit" name="submit" id="submit"><br /></td></tr>
</form><br />
</table>
</div>
</body>
Still have an issue with this, could you possibly help me? Thanks again!
Firstly, in your question, all the answers have the same id='questionone'. You need to remove these ids.
To check if a particular name group is checked you can use:
function isAnswered(name) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((input.name === name) && (input.checked)) {
return true;
}
}
return false;
}
You can then test each question group with the following code:
if (!isAnswered("Qone")) {
alert("Question one must be completed");
return false;
}
Can you show the whole form? In the meantime, try this:
function checkForm() {
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Please enter a valid e-mail address");
return false;
}
if (document.getElementById("questionone").checked) {
alert("Option one is selected");
} else if (document.getElementById("questiontwo").checked) {
alert("Option two is selected");
} else if (document.getElementById("questionthree").checked) {
alert("Option three is selected");
} else if (document.getElementById("questionfour").checked) {
alert("Option four is selected");
} else {
alert("No option is selected");
}
}
And this is what i'm trying to tell you, put unique id's on your inputs to get their values in the function:
<tr>
<td class="answer">
<label>8.45 seconds</label>
<input type="radio" value="Aone" name="Qone" id="questionone" />
</td>
<td class="answer">
<label>9.58 seconds</label>
<input type="radio" value="Atwo" name="Qtwo" id="questiontwo" />
</td>
<td class="answer">
<label>10.12 seconds</label>
<input type="radio" value="Athree" name="Qthree" id="questionthree" />
</td>
<td class="answer">
<label>9.32 seconds</label>
<input type="radio" value="Afour" name="Qfour" id="questionfour" />
</td>
</tr>

Categories

Resources