We are trying to develop a very simple HTML/JavaScript advising tool for students. It gives advice on which courses to take after the student checks radio buttons describing his or her high school GPA and standardized test score. The current version works correctly in both Chrome and Firefox, displaying its results after both radio buttons have been checked. In IE11, the page displays and the user can check buttons, but no response is given when the second button is checked. How should we make this independent of (current) browser?
A stripped-down version is posted below, containing enough code to demonstrate the basic behavior and problem.
function calc() {
//sets all the variables to blank
gpa109 = ""
gpa115 = ""
note = ""
//The value of the GPA radio button input is set in the GPA variable (first button=1, etc...)
GPA = document.data.GPA.value
//The value of the ACT radio button input is set in the ACT variable (first button=1, etc...)
ACT = document.data.ACT.value
//Use if-then statements to assign gpa output values to variables based on GPA and ACT inputs
//gpa output variables are gpa109, gpa115, gpa109120, etc...
//the note in the text box at the end is in variable "note"
if (GPA == 1) {
if (ACT == 1) {
gpa109 = "0.91"
}
}
if (GPA == 1) {
if (ACT == 1) {
gpa115 = "No Data"
}
}
if (GPA == 1) {
if (ACT == 2) {
gpa109 = "1.50"
}
}
if (GPA == 1) {
if (ACT == 2) {
gpa115 = "No Data"
}
}
if (GPA == 2) {
if (ACT == 1) {
gpa109 = "1.68"
}
}
if (GPA == 2) {
if (ACT == 1) {
gpa115 = "No Data"
}
}
if (GPA == 2) {
if (ACT == 2) {
gpa109 = "1.98"
}
}
if (GPA == 2) {
if (ACT == 2) {
gpa115 = "1.27"
}
}
if (GPA == 1) {
if (ACT == 1) {
note = "we are worried about you."
}
}
if (GPA == 1) {
if (ACT == 2) {
note = "slacked off a bit in high school, did you not?"
}
}
if (GPA == 2) {
if (ACT == 1) {
note = "you are a classic bad standardized test taker."
}
}
if (GPA == 2) {
if (ACT == 2) {
note = "you should probably apply to a better college."
}
}
//These statements put all the values determined by the if-then statements into the document
document.data.gpa109.value = gpa109
document.data.gpa115.value = gpa115
document.data.note.value = note
}
<form name="data">
<table COLS=4 cellpadding=2 border=1 align=center>
<tr>
<td COLSPAN="4">
<center><b><font size=+2>
<p>
Advising Tool
</p></font></b>
</center>
</td>
</tr>
<tr>
<td COLSPAN="2">
<center><font size=+1>
<p>
What was your High School GPA?
</p>
</font>
</center>
</td>
<td COLSPAN="2">
<center><font size=+1>
<p>
What was your ACT Math subscore?
<p>
</font>
</center>
</td>
</tr>
<tr>
<td COLSPAN="2">
<center>
<font size=+1>
<P>
<input type="radio" name="GPA" value="1" onclick="calc();"> Less than 3.5<br>
<input type="radio" name="GPA" value="2" onclick="calc();"> 3.5 or greater<br>
</P></font>
</center>
</td>
<td COLSPAN="2">
<center><font size=+1>
<P>
<input type="radio" name="ACT" value="1" onclick="calc();"> Less than 26<br>
<input type="radio" name="ACT" value="2" onclick="calc();"> 26 or greater<br>
</P> </font>
</center>
</td>
</tr>
<tr>
<td COLSPAN="4" align="center">
<font size=+1>
<br>
Over the past 5 years, students with similar high school GPAs and ACT Math<br>scores had the following average GPA in their introductory CHM courses.
<br>
<br>
</font>
</td>
</tr>
<tr>
<td align="right">
Classes Taken
</td>
<td>
Average GPA
</td>
</tr>
<tr>
<td align="right">
CHM 109 Only
</td>
<td>
<input name="gpa109" size="10" type="text">
</td>
<tr>
<td align="right">
CHM 115 Only
</td>
<td>
<input type="text" name="gpa115" size="10">
</td>
<tr>
<td COLSPAN="4" align="center">
<textarea rows="2" cols="100" name="note">
</textarea>
</td>
</tr>
</table>
</form>
Your problem is here, document.data.GPA.value, where the GPA is an array of objects, so you need to access the value like this
document.data.GPA[0].value;
As a side note, the code you posted is filled with obsolete elements, like center, font, so I recommend you do a clean up, and using table for layout is outdated, check out for example flexbox, which is excellent for this
Update
What I mean with read a value of an array of objects is to do something like this
var v = document.querySelectorAll('input[name=GPA]');
for(var i = 0; i < v.length; i++){
if(v[i].checked){
GPA = v[i].value;
}
}
There is also document.querySelector
GPA = document.querySelector('input[name=GPA]:checked').value;
Or the classic form.elements syntax
document.data.elements['GPA'].value;
Related
This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 3 years ago.
Hello guys I'm really new to javascript,
I want an alert message to appear if the user pressed on check,
to see if the input was right or wrong,
and I've been trying for so long but it's not working no matter what, it's just a simple code.
I'm really suffering with this for hours, trying to figure why no alert message appears when I press on the check button.
Would be really grateful for any help or any tip, many thanks!!
function myFunction() {
var x = document.getElementById("f").value;
var z = document.getElementById("s").value;
var c = document.getElementById("e").value;
var v = document.getElementById("p").value;
var b = document.getElementById("p1").value;
if (isNaN(x) || x = "") {
alert("First Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(z) || z = "") {
alert("Second Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(c) || c = "") {
alert("Email input is wrong");
} else {
alert("Input is ok");
}
if (v = "") {
alert("Input is wrong");
} else {
alert("Input is ok");
}
if (b = "" || b !== v) {
alert("Password does not match");
else {
alert("Input is ok");
}
}
}
<div class="event">
<h1> Event Planning</h1>
</div>
<div class="back">
<table border="1">
<form action="submit.php" method="post">
<tr>
<th colspan="2"> Sign UP</th>
</tr>
<tr>
<td> First Name </td>
<td> <input type="text" name="FirstName" id="f"></td>
</tr>
<tr>
<td> Second Name</td>
<td> <input type="text" name="SecondName" id="s"></td>
</tr>
<tr>
<td> Email Address</td>
<td> <input type="email" name="email" id="e"> </td>
</tr>
<tr>
<td> Password</td>
<td> <input type="password" name="psd" id="p"> </td>
</tr>
<tr>
<td> Repeat Password</td>
<td> <input type="password" name="psd2" id="p1"> </td>
</tr>
<tr>
<td colspan="2"> <input type="submit" name="submit" value="submit">
<button type="button" id="but" onclick="myFunction()">Check</button></td>
</tr>
</form>
</table>
You have a few syntax errors in your function.
Javascript requires == (or ===) for comparisons.
You also need to add a curly brace } before the else after "Password does not match", and remove one after the following "Input is ok".
I'm trying to use a javascript method to validate my form but it doesn't seem to be working. No dialog box pops up warning me of any errors even if an empty form is submitted. What could be the error?
(Please Note: The JS File has a method defined for a time-stamp that I am currently not using in my form tag. I need some help with calling two functions as well.)
Here's the code:
function setDate() {
document.getElementById('date').value = new Date();
}
function validateForm() {
var a = document.getElementById('name').value;
var b = document.getElementById("contact1").value;
var blen = b.length;
var c = document.getElementById("address1").value;
var d = document.getElementById("stblimit").value;
var dlen = d.length;
var e = document.getElementById("creditlimit").value;
var f = document.getElementById("commission").value;
var g = document.getElementById("servicecharges").value;
//DATE var h = document.forms["addRetailer"]["date"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
} else if (b == null || b == "" || blen == 0 || blen > 10 || blen < 10) {
alert("Enter a valid number");
return false;
} else if (c == null || c == "") {
alert("Primary Address must be filled out");
return false;
} else if (d == null || d == "" || dlen == 0 || dlen < 0) {
alert("Set Box Top Limit must be filled with a valid number");
return false;
} else if (e == null || e == "") {
alert("Credit Limit must be filled out");
return false;
} else if (f == null || f == "") {
alert("Commission Percentage must be filled out");
return false;
} else if (g == null || g == "") {
alert("Service Charges must be filled out");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="formvalidation.js" type="text/javascript"></script>
<title>Register Retailer</title>
</head>
<body>
<h1>Retailer Information</h1>
<form name="addRetailer" action="RetailerController" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" id="name"></input>
</td>
</tr>
<tr>
<td>Contact Number 1</td>
<td>
<input type="text" name="contact1" id="contact1"></input>
</td>
</tr>
<tr>
<td>Contact Number 2</td>
<td>
<input type="text" name="contact2" id="contact2"></input>
</td>
</tr>
<tr>
<td>Address Line 1</td>
<td>
<input type="text" name="address1" id="address1"></input>
</td>
</tr>
<tr>
<td>Address Line 2</td>
<td>
<input type="text" name="address2" id="address2"></input>
</td>
</tr>
<tr>
<td>City</td>
<td>
<input type="text" name="city" id="city"></input>
</td>
</tr>
<tr>
<td>State</td>
<td>
<input type="text" name="state" id="state"></input>
</td>
</tr>
<tr>
<td>Pin Code</td>
<td>
<input type="text" name="pin" id="pin"></input>
</td>
</tr>
<tr>
<td>Set Top Box Limit</td>
<td>
<input type="text" name="stblimit" id="stblimit" value="0"></input>
</td>
</tr>
<tr>
<td>Credit Limit</td>
<td>
<input type="text" name="creditlimit" id="creditlimit"></input>
</td>
</tr>
<tr>
<td>Commission Percentage</td>
<td>
<input type="text" name="commission" id="commission" value="0.0"></input>
</td>
</tr>
<tr>
<td>Service Charges</td>
<td>
<input type="text" name="servicecharges" id="servicecharges"></input>
</td>
</tr>
<tr>
<td>Date of Registration</td>
<td>
<input type="text" name="date" id="date"></input>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" value="registerCustomer" name="action"></input>
<input type="submit" value="Register"></input>
</td>
</tr>
</table>
</form>
<br>
<br>Click
Home To Return To The Main Screen
</body>
</html>
EDIT:
Here is a screenshot of my Eclipse IDE workspace. My js file and html file aren't in the same sub-folder, although they are under 'Web Content'. Could that be the issue?
Screenshot of Eclipse IDE Workspace
You may not have linked your JS file properly.
Looking at your screenshot I noticed you're using Tomcat and Java EE, which follows Unix style syntax for it's directory on the web server.
Your directory:
-Webcontent/
-WEB-INF/
+addRetailer
-JavaScript/
+validateForm.js
So, your HTML file is in WEB-INF which is under Webcontent and the form validator is under javascript, also under webcontent.
There's three solutions I have for this:
Move the JavaScript folder into WEB-INF and change the script reference to: "JavaScript/formvalidation.js"
Change the script reference to jump 'up' a directory layer using the double-dot'..' which should end up being: "../JavaScript/formvalidator.js"
Use HTML5's form validation instead, which doesn't need JavaScript. and is much neater. You can find details on the Mozilla Dev Network here.
Using Chrome, it seems to work for me:
The only thing that I changed is that I removed the link to the external JS file. It is possible the error is there and preventing your code from running. Check that file.
I have been going insane over the last few days trying to figure this out, and I am at a complete loss as to what to do.
For an assignment I have to do for class, we have to analyse the following JavaScript code and correct the errors. I have managed to figure out most of it, but am stuck on this last part.
Whenever I click the "Calculate" button, it is returning "$NaN.undefined" for the monthly payment amount. I have gone over the code over and over again, and everything seems to match what it shows in my textbook, so I have no idea what I need to change to make it work properly.
I just started learning JavaScript a few days ago, so I am VERY new at this. Any help or guidance anyone could give me would be extremely appreciated.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Make10-1 Oakwood Mortgage</title>
<script type="text/javascript">
<!--Hide from old browsers
var thisMsg=" ** See us for your auto loan financing needs!!! ** "
var beginPos=0
function scrollingMsg() {
msgForm.scrollingMsg.value=thisMsg.substring(beginPos,thisMsg.length)+thisMsg.substring(0,beginPos)
beginPos+=1
if (beginPos > thisMsg.length) {
beginPos=0
}
window.setTimeout("scrollingMsg()",200)
}
var salesAmt
var loanAmt
var loanRate
var loanYears
function valSaleDownAmt() {
var salesAmt=parseInt(LoanCalc.SaleAmt.value,10)
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
LoanCalc.SaleAmt.value = ""
LoanCalc.SaleAmt.focus()
}
else {
var DownPayment=parseFloat(LoanCalc.DownPmt.value)/100
if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
LoanCalc.DownPmt.value = " "
LoanCalc.DownPmt.focus()
}
else {
var amtDown = salesAmt*DownPayment
var loanAmt = salesAmt-amtDown
LoanCalc.LoanAmt.value = dollarFormat(loanAmt.toFixed(2))
LoanCalc.Rate.focus()
}
}
}
function CalcLoanAmt() {
loanRate=parseFloat(LoanCalc.Rate.value)
if (isNaN(loanRate) || (loanRate <= 0)) {
alert("The interest rate is not a valid number!")
LoanCalc.Rate.value = ""
LoanCalc.Rate.focus()
}
else {
loanYears=parseInt(LoanCalc.Years.selectedIndex)
if (isNaN(loanYears) || (loanYears < 1)) {
alert("Please select a valid number of years from the list!")
LoanCalc.Years.selectedIndex = "0"
LoanCalc.Years.focus()
}
else {
var monthlyPmt = monthly(loanAmt,loanRate,loanYears)
LoanCalc.Payment.value=dollarFormat(monthlyPmt.toString())
}
}
}
function monthly(loanAmt,loanRate,loanYears) {
var Irate = loanRate/1200
var Pmts = loanYears*12
var Amnt = loanAmt * (Irate / (1 - (1 / Math.pow(1+Irate,Pmts))))
return Amnt.toFixed(2)
}
function dollarFormat(valuein) {
var formatValue = ""
var formatDollars = ""
formatAmt = valuein.split(".",2)
var dollars = formatAmt[0]
var dollarLen = dollars.length
if (dollarLen > 3) {
while (dollarLen > 0) {
tempDollars = dollars.substring(dollarLen - 3,dollarLen)
if (tempDollars.length == 3) {
formatDollars = "," + tempDollars + formatDollars
dollarLen = dollarLen - 3
} else {
formatDollars = tempDollars + formatDollars
dollarLen = 0
}
}
if (formatDollars.substring(0,1) == ",")
dollars = formatDollars.substring(1,formatDollars.length)
else
dollars = formatDollars
}
var cents = formatAmt[1]
var formatValue="$"+dollars+"."+cents
return formatValue
}
function popUpAd() {
open("make10-1notice.html","noticeWin","width=520,height=270")
}
function lastModified() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
displayDateLast.innerHTML="<span style='font-family:Arial, Helvetica, sans-serif; font-size:9px; font-weight:bold'>This document was last modified "+lastModDate+"</span>"
}
//-->
</script>
<style type="text/css">
<!--
body {
background-image: url(financial_symbol.jpg);
}
-->
</style>
</head>
<body onload="scrollingMsg(); popUpAd(); lastModified()">
<div align="center">
<p align="center"><img src="make10-1banner.jpg" width="750" height="120" alt="banner" /></p>
<form id="msgForm" action="">
<p style="text-align:center"><input type="text" name="scrollingMsg" size="25" /></p>
</form>
</div>
<div style="font-family:Arial, Helvetica, sans-serif">
<h3 align="center">Home Loan Payment Calculator</h3>
<form id="LoanCalc" action="">
<table width="346" align="center" cellspacing="3">
<tr>
<td align="right">
<span style="color:#cc0000">*</span>Sale Price:
</td>
<td><input type="text" name="SaleAmt" id="SaleAmt" size="9" /></td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Down Payment as a percent
</td>
<td><input name="DownPmt" type="text" id="DownPmt" size="4" onblur="valSaleDownAmt()" />
%</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Interest Rate (e.g. 5.9):
</td>
<td><input type="text" name="Rate" id="Rate" size="4" /> %
</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Select Number of Years:
</td>
<td><select name="Years" id="Years">
<option selected="selected">Select Years</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="40">40</option>
</select></td>
</tr>
<tr>
<td align="right">
<input name="button" type="button" value="Calculate" onclick="CalcLoanAmt()" />
</td>
<td>
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Loan Amount
</td>
<td>
<input name="LoanAmt" type="text" id="LoanAmt" size="9" />
</td>
</tr>
<tr>
<td align="right">
<span style="font-weight:bolder">Monthly Payment</span>:
</td>
<td><input type="text" name="Payment" id="Payment" value=" " size="12" /></td>
</tr>
</table>
<p style="color:#cc0000; text-align:center">* Indicates a required field.</p>
</form>
</div>
<div id="displayDateLast" style="margin-left:5%">
</div>
</body>
</html>
I've made some changes in two of your functions, and rest of the functions and html are fine. And it worked, please check it:-
function valSaleDownAmt() {
var saleAmtInput = document.getElementById("SaleAmt"),
salesAmt=parseInt(saleAmtInput.value,10),
downPaymentInput = document.getElementById('DownPmt'),
DownPayment=parseFloat(downPaymentInput.value)/100,
loanRateInput = document.getElementById('Rate'),
loanRate=parseFloat(loanRateInput.value),
loanYearsInput = document.getElementById('Years'),
loanYears=parseInt(loanYearsInput.value);
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
saleAmtInput.value = ""
saleAmtInput.focus()
}
else if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
downPaymentInput.value = " "
downPaymentInput.focus()
} else if (isNaN(loanRate) || (loanRate <= 0)) {
alert("The interest rate is not a valid number!")
loanRateInput.value = ""
loanRateInput.focus()
} else if (isNaN(loanYears) || (loanYears < 1)) {
alert("Please select a valid number of years from the list!")
}
else {
CalcLoanAmt(salesAmt,DownPayment,loanRate,loanYears);
}
}
function CalcLoanAmt(salesAmt,DownPayment,loanRate,loanYears) {
var amtDown = salesAmt*DownPayment,
loanAmt = salesAmt-amtDown,
monthlyPmt = monthly(loanAmt,loanRate,loanYears);
document.getElementById('Payment').value=dollarFormat(monthlyPmt.toString());
document.getElementById('LoanAmt').value = loanAmt;
}
That means, no need of the global variables like:-
var salesAmt
var loanAmt
var loanRate
var loanYears
You can remove this variables.
And you have to modify in two places in your html:-
One is:-
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Down Payment as a percent
</td>
<td><input name="DownPmt" type="text" id="DownPmt" size="4" />
%</td>
</tr>
That means, you have to remove the function call on blur of the input box.
And the second is:-
<tr>
<td align="right">
<input name="button" type="button" value="Calculate" onclick="valSaleDownAmt()" />
</td>
<td>
<input name="Reset" type="reset" />
</td>
</tr>
That means you've to call the function valSaleDownAmt instead of the function CalcLoanAmt, on click on the calculate button.
The functionality of the previous code was same, but that would raise some issue in certain case, so i think it is more proper code. Try it.
A great opportunity to learn to use the debugger to step through your code. Add a couple of breakpoints in your functions that calculate the values and set a watch on the variables that are used to calculate the monthly payment and determine where they start returning an invalid value. You'll find the offending code in no time :)
You can read about the debugger for Chrome at https://developer.chrome.com/devtools/docs/javascript-debugging. There is also a decent introductory video at https://www.youtube.com/watch?v=htZAU7FM7GI.
Also, although not technically required, you should be ending your statements with a semi-colon. If you don't know all of the various statement rules for Javascript, leaving out the semi-colons can have unexpected results.
I think Bill has the best "answer". But I think in this particular example, you've got loanAmt defined in 2 places (var loanAmt).
I think you don't want it defined in the 2nd place (the local variable).
When CalcLoadAmount calls Monthly right now, the value of `loadAmt" isn't defined. I tried removing the 2nd variable declaration, and it might be the fix you need....
function valSaleDownAmt() {
var salesAmt=parseInt(LoanCalc.SaleAmt.value,10)
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
LoanCalc.SaleAmt.value = ""
LoanCalc.SaleAmt.focus()
}
else {
var DownPayment=parseFloat(LoanCalc.DownPmt.value)/100
if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
LoanCalc.DownPmt.value = " "
LoanCalc.DownPmt.focus()
}
else {
var amtDown = salesAmt*DownPayment
//
// THIS IS THE LINE I CHANGED RIGHT BELOW THIS COMMENT**
//
loanAmt = salesAmt-amtDown
LoanCalc.LoanAmt.value = dollarFormat(loanAmt.toFixed(2))
LoanCalc.Rate.focus()
}
}
}
The problem has to do with the loanAmt variable as Brad Parks mentioned (it won't let me comment). If you add the below code to the beginning of the CalcLoanAmt(), the function will work. Although there are probably better ways of doing this, this code will fix it. Good luck!
loanAmt=parseInt(LoanCalc.SaleAmt.value,10) - (parseFloat(LoanCalc.DownPmt.value)/100)
I think the problem arises because your values remain undefined throughout. At the top of your script where your variables are declared, there are no default values given. Try giving them default values of 0. You shouldn't get undefined anymore. This won't solve your problem entirely but it's a good start. Also you should try making the variables global by putting this before the variables. So for the variables at the top do
this.salesAmt = 0
this.loanAmt = 0
this.loanRate = 0
this.loanYears = 0
and everywhere they appear in your code put this before them.
I'm trying to work this form so when the first radio button is selected, run a certain validation. When the second radio button is selected, run a different validation, etc. Currently using Alerts to check the functionality, but whichever radio button I choose I do not receive any feedback.
javascript function
<script type="text/javascript">
function validateDays() {
if (document.form1.radio1[0].checked == true) {
alert("You have selected Option 1");
}
else if (document.form1.radio1[1].checked == true) {
alert("You have selected Option 2");
}
else if (document.form1.radio1[2].checked == true) {
alert("You have selected Option 3");
}
else {
// DO NOTHING
}
}
}
</script>
html input code
<input name="radio1" type="radio" value="option1" id="option1" onClick="validateDays();">
<input name="radio1" type="radio" value="option2" id="option2" onClick="validateDays();">
<input name="radio1" type="radio" value="option3" id="option3" onClick="validateDays();">
How do I get a different alert depending on which radio button is checked?
Eventually, each radio button will limit the number of checkboxes further down the form the user is able to select - which is why I cannot work this validation purely in to the onClick()
MORE FULL CODE - ON REQUEST
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery('#3daypass').click(function mattcode() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
});
jQuery('#2daypass , #1daypass').click(function mattcode() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
});
});
</script>
<script type="text/javascript">
function validateDays() {
if (document.getElementById('3daypass').checked) {
alert("You have selected Option 1");
}
else if (document.getElementById('2daypass').checked) {
alert("You have selected Option 2");
}
else if (document.getElementById('1daypass').checked) {
alert("You have selected Option 3");
}
else {
// DO NOTHING
}
}
}
</script>
<tr>
<td colspan="5" align="left"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="65%" valign="top"><table width="100%" height="100%" border="0" cellpadding="2" cellspacing="0">
<tr valign="middle">
<td height="18" colspan="2" align="left" bgcolor="#000000"><span class="boxheader"><strong> Conference Pass</strong></span> <span class="bodycopyWhite"> - (Please select a day pass below)</span></td>
</tr>
<tr valign="middle">
<td colspan="2" align="left" bgcolor="#EBEBEB"><img src="spacer.gif" width="1" height="3"></td>
</tr>
<tr bgcolor="#EBEBEB">
<td align="center" valign="top" bgcolor="#EBEBEB"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="7%"><input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="Payment_Total(); check_code(); Vat_Total(); validateDays();"></td>
<td width="93%" class="bodyNormal"><strong>Three-day</strong> open delegate pass</td>
</tr>
<tr>
<td><input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="Payment_Total(); check_code(); Vat_Total(); validateDays();"></td>
<td class="bodyNormal"><strong>Two-day</strong> open delegate pass</td>
</tr>
<tr>
<td><input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="Payment_Total(); check_code(); Vat_Total(); validateDays();"></td>
<td class="bodyNormal"><strong>One-day</strong> open delegate pass</td>
</tr>
</table></td>
</tr>
<tr valign="middle">
<td colspan="2" align="left" bgcolor="#EBEBEB"><img src="spacer.gif" width="1" height="3"></td>
</tr>
</table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td height="20" colspan="2" bgcolor="#000000" class="boxheader"><strong> Please select the days you will be attending</strong></td>
</tr>
<tr>
<td width="9%" bgcolor="#EBEBEB"><input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb"></td>
<td width="91%" bgcolor="#EBEBEB" class="bodycopy">Tuesday 5 February 2013 </td>
</tr>
<tr>
<td bgcolor="#EBEBEB"><input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb"></td>
<td bgcolor="#EBEBEB" class="bodycopy">Wednesday 6 February 2013 </td>
</tr>
<tr>
<td bgcolor="#EBEBEB"><input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb"></td>
<td bgcolor="#EBEBEB" class="bodycopy">Thursday 7 February 2013 </td>
</tr>
Apologies for the messy code - This was written in 2005 by someone else (with an apparent phobia of CSS) - see what I have to work with?!
function validateDays() {
if (document.getElementById("option1").checked == true) {
alert("You have selected Option 1");
}
else if (document.getElementById("option2").checked == true) {
alert("You have selected Option 2");
}
else if (document.getElementById("option3").checked == true) {
alert("You have selected Option 3");
}
else {
// DO NOTHING
}
}
You need to use == or === for comparison. = assigns a new value.
Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).
You must use the equals operator not the assignment like
if(document.form1.radio1[0].checked == true) {
alert("You have selected Option 1");
}
Full validation example with javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Radio button: full validation example with javascript</title>
<script>
function send() {
var genders = document.getElementsByName("gender");
if (genders[0].checked == true) {
alert("Your gender is male");
} else if (genders[1].checked == true) {
alert("Your gender is female");
} else {
// no checked
var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
document.getElementById('msg').innerHTML = msg;
return false;
}
return true;
}
function reset_msg() {
document.getElementById('msg').innerHTML = '';
}
</script>
</head>
<body>
<form action="" method="POST">
<label>Gender:</label>
<br />
<input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
<br />
<input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
<br />
<div id="msg"></div>
<input type="submit" value="send>>" onclick="return send();" />
</form>
</body>
</html>
Regards,
Fernando
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>