checked checkbox to enable text field with validation - javascript

I have a Paypal form which has been built using some borrowed code. The main purpose of the form is to add some optional extras to a standard product and send that data to the paypal checkout. It seems to be working quite well, but...
I have a text field that I want to be required when the related checkbox is checked and for it to be disabled, and therefore not required when its unchecked.
Crucially I need the data in the text field to be sent to the paypal shopping basket.
I have validation on another text field which will always be required, that works and sends the data to Paypal, but I'm a javascript newbie and can't get to grips with the second field.
This is the borrowed javascript
function Dollar (val) { // force to valid dollar amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
var amt,des,obj,val,op1a,op1b,op2a,op2b,itmn;
function ChkTok (obj1) {
var j,tok,ary=new Array (); // where we parse
ary = val.split (" "); // break apart
for (j=0; j<ary.length; j++) { // look at all items
// first we do single character tokens...
if (ary[j].length < 2) continue;
tok = ary[j].substring (0,1); // first character
val = ary[j].substring (1); // get data
if (tok == "#") amt = val * 1.0;
if (tok == "+") amt = amt + val*1.0;
if (tok == "%") amt = amt + (amt * val/100.0);
if (tok == "#") { // record item number
if (obj1.item_number) obj1.item_number.value = val;
ary[j] = ""; // zap this array element
}
// Now we do 3-character tokens...
if (ary[j].length < 4) continue;
tok = ary[j].substring (0,3); // first 3 chars
val = ary[j].substring (3); // get data
if (tok == "s1=") { // value for shipping
if (obj1.shipping) obj1.shipping.value = val;
ary[j] = ""; // clear it out
}
if (tok == "s2=") { // value for shipping2
if (obj1.shipping2) obj1.shipping2.value = val;
ary[j] = ""; // clear it out
}
}
val = ary.join (" "); // rebuild val with what's left
}
function StorVal () {
var tag;
tag = obj.name.substring (obj.name.length-2); // get flag
if (tag == "1a") op1a = op1a + " " + val;
else if (tag == "1b") op1b = op1b + " " + val;
else if (tag == "2a") op2a = op2a + " " + val;
else if (tag == "2b") op2b = op2b + " " + val;
else if (tag == "3i") itmn = itmn + " " + val;
else if (des.length == 0) des = val;
else des = des + ", " + val;
}
function ReadForm (obj1, tst) { // Read the user form
var i,j,pos;
amt=0;des="";op1a="";op1b="";op2a="";op2b="";itmn="";
if (obj1.baseamt) amt = obj1.baseamt.value*1.0; // base amount
if (obj1.basedes) des = obj1.basedes.value; // base description
if (obj1.baseon0) op1a = obj1.baseon0.value; // base options
if (obj1.baseos0) op1b = obj1.baseos0.value;
if (obj1.baseon1) op2a = obj1.baseon1.value;
if (obj1.baseos1) op2b = obj1.baseos1.value;
if (obj1.baseitn) itmn = obj1.baseitn.value;
for (i=0; i<obj1.length; i++) { // run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one") { // just selects
if (obj.name == "quantity" ||
obj.name == "amount") continue;
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
ChkTok (obj1); // check for any specials
if (obj.name == "on0" || // let this go where it wants
obj.name == "os0" ||
obj.name == "on1" ||
obj.name == "os1") continue;
StorVal ();
} else
if (obj.type == "checkbox" || // just get checkboxex
obj.type == "radio") { // and radios
if (obj.checked) {
val = obj.value; // the value of the selection
ChkTok (obj1);
StorVal ();
}
} else
if (obj.type == "select-multiple") { //one or more
for (j=0; j<obj.options.length; j++) { // run all options
if (obj.options[j].selected) {
val = obj.options[j].value; // selected value (default)
ChkTok (obj1);
StorVal ();
}
}
} else
if (obj.name == "size") {
val = obj.value; // get the data
if (val == "" && tst) { // force an entry
alert ("Enter data for " + obj.name);
return false;
}
StorVal ();
} else
if (obj.name == "stamp") {
val = obj.value; // get the data
//if (val == "" && tst) { // force an entry
// alert ("Enter data for " + obj.name);
// return false;
//}
StorVal ();
}
}
// Now summarize stuff we just processed, above
if (op1a.length > 0) obj1.on0.value = op1a;
if (op1b.length > 0) obj1.os0.value = op1b;
if (op2a.length > 0) obj1.on1.value = op2a;
if (op2b.length > 0) obj1.os1.value = op2b;
if (itmn.length > 0) obj1.item_number.value = itmn;
obj1.item_name.value = des;
obj1.amount.value = Dollar (amt);
if (obj1.tot) obj1.tot.value = "£" + Dollar (amt);
}
and this is the html
<form action="https://www.paypal.com/cgi-bin/webscr" name="weboptions" method="post" onsubmit="this.target='_blank'; return ReadForm(this, true);">
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="add" value="1" />
<input type="hidden" name="business" value="craig#craigomatic.co.uk" />
<input type="hidden" name="shipping" value="0.00">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="return" value="">
<input type="hidden" name="item_name" value />
<input type="hidden" name="amount" value />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="lc" value="US" />
<input type="hidden" name="bn" value="PP-ShopCartBF">
<input type="hidden" name="basedes" value="Collar">
<h4>Collar details...</h4>
<div>
<p>Matching lamb nappa lining <br />
with antique brass finished hardware</p>
<div>
<p>Pick a colour:</p>
<p>Chose a width:</p>
<p>Tell us the Size:<br />
in cms (?)</p>
</div>
<div>
<p>
<select name="colour" onclick="ReadForm (this.form, false);" size="1">
<option value="Black +55.00">Black</option>
<option value="Brown +55.00">Brown</option>
<option value="Tan +55.00">Tan</option>
</select>
</p>
<p>
<select name="width" onclick="ReadForm (this.form, false);" size="1">
<option value="1 and quarter inch">1¼ inch</option>
<option value="1 and half inch">1½ inch</option>
</select>
</p>
<p><input name="size" type="text" class="size"></p>
<p></p>
</div>
</div>
<h4>Optional extras...</h4>
<div>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Double D +1.50"
name ="DoubleD">
Double D Me (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Max Me +1.50"
name ="MaxMe">
Max Me! (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Match Me +1.50"
name ="MatchMe">
Match Me (£1.50)
</label>
</p>
<p>
<label>
<input type ="checkbox" onclick="ReadForm (this.form, false);"
value ="Stamp Me +1.50"
name ="StampMe">
Stamp Me (£1.50)</label>
</p>
<p><input name="stamp" type="text" class="lettering" maxlength="12"></p>
</div>
<p>Total:<input class="nbor" type="text" name="tot" size="7" value="£55.00" /> <input class="buy" type="submit" value="Buy Me" name="B1"></p>
</form>
If your wondering you can find the page in question here http://booleather.co.uk/option1/bronze-bronco.php
Any help would be much appreciated.

Give this code a try:
if (val == "" && obj1.elements["StampMe"].checked) {
// if the value of the stamp text field is empty and the user has checked the StampMe box
alert ("Enter data for " + obj.name);
return false;
}
(instead of)
//if (val == "" && tst) { // force an entry
// alert ("Enter data for " + obj.name);
// return false;
//}

Related

Student Object Program Errors

I have a program that is suppose to ask the user for their ID, First Name, Last Name, select a Rank (grade level), and the GPA. After all fields go through error checking, the data should then be put into an object called student. Next the student object should be pushed to the Summary Array. Displaying the first and last name, next line ID, next line Class Rank, next line GPA.
UPDATE CURRENTLY: all error checking (if/elses) works! Secondly, only the "--------" happens when Add Student is pressed besides the error checking.
Full Code:
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
studentID = document.getElementById('Text1').value;
studentFirst = document.getElementById('Text2').value;
studentLast = document.getElementById('Text3').value;
Rank = document.getElementById('Select1').value;
studentGPA = document.getElementById('Text4').value;
if (!studentList.includes(studentID)) {
if (studentID != '') {
if (studentFirst != '') {
if (studentLast != '') {
if (Rank != -1) {
if (studentGPA != '') {
if (studentGPA > 0 && studentGPA < 4) {
var Student = {
studentID: document.getElementById('Text1').value,
studentFirst: document.getElementById('Text2').value,
studentLast: document.getElementById('Text3').value,
Rank: document.getElementById('Select1').value,
studentGPA: document.getElementById('Text4').value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>"
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option value="-1">(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
You need to initialize Summary to an empty array. Otherwise, Summary.push() gets an error because you can't push onto undefined.
The index of the prompt option in the Rank menu is 0, not 1, so you should check for that in the validation.
The Create() function reassigns all the variables that contain the input elements, replacing them with their values. You should use different variables, or just use the .value properties of the global variables.
You need to convert the value of Rank to a number before comparing with numbers.
You're missing a + at the end of the first line of the string you're appending to the DIV, so you're only adding the ---- line.
When checking for duplicates, you need to compare studentID.value with the studentID property of the array element, not the whole array element. And you should be searching Summary, not studentList.
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
if (!Summary.find(s => s.studentID == studentID.value)) {
if (studentID.value != '') {
if (studentFirst.value != '') {
if (studentLast.value != '') {
if (Rank.selectedIndex != 0) {
if (studentGPA.value != '') {
let GPAVal = parseFloat(studentGPA.value);
if (GPAVal > 0 && GPAVal < 4) {
var Student = {
studentID: studentID.value,
studentFirst: studentFirst.value,
studentLast: studentLast.value,
Rank: Rank.value,
studentGPA: studentGPA.value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>" +
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option>(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
Rank has no selectedIndex because Rank is not an element or node.
Rank = document.getElementById('Select1').value;
You should set the value attribute on your option tags.
<option value="-1">(Select a Rank)</option>
if (Rank != -1) {

External js file not working with HTML file

Currently I am building a website which this page uses an external javascript file, one of the main function is that in the form if the user does not enter anything or enter the wrong value and clicks on the submit button, a error message will show up above each section, but unfortunately mine when I click on the submit button it will still submit and will not show any error, I suspect that the Javascript file is not linked properly but I did set the path correctly as you can see in the picture and the on the HTML page.
HTML File:
<meta charset="utf-8" />
<meta name="description" content="Demonstrates some basic HTML content elements and CSS" />
<meta name="keywords" content="html, css" />
<meta name="author" content="Jordan Siow" />
<link rel = "stylesheet" type = "text/css" href = "styles/style.css"/>
<script type="text/JavaScript" src="scripts/apply.js"></script>
<title>Apply </title>
<section class="front_title">
<p> Company XIT <img src="styles/images/logo.png" alt="logo" height="70" width="250"/>
</p>
</section>
<section class="topnav">
<table>
<tr>
<td >
Main
</td>
<td >
Jobs
</td>
<td id="current">
Apply
</td>
<td>
About
</td>
<td>
Enhancements
</td>
</tr>
</table>
</section>
<section id="style_apply">
<h2>Submit your Application!</h2>
<form method="post" id="apply_form" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p><span id="job_id_error" class="error"></span></p>
<p><label for="jobid">Job Reference Number</label>
<input type="text" name="jobid" id="jobid" maxlength="5" pattern="[0-9]{5}" /></p>
<p><span id="firstname_error" class="error"></span></p>
<p><label for="firstname">First Name</label>
<input type ="text" name="First Name" id="firstname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<p><span id="lastname_error" class="error"></span></p>
<p><label for="lastname">Last Name</label>
<input type ="text" name="Last Name" id="lastname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<br/>
<p><span id="dob_error" class="error"></span></p>
<p><label for="dateofbirth">Date of Birth</label>
<input type="date" name="Date of Birth" id="dateofbirth" /></p>
<br/>
<br/>
<label>Gender</label>
<p><span id="gender_error" class="error"></span></p>
<fieldset id="gender">
<label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" />
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Others</label>
<input type="radio" id="other" name="Gender" value="other"/>
<label for="rathernotsay">Rather Not Say</label>
<input type="radio" id="rathernotsay" name="Gender" value="rathernotsay"/>
</fieldset>
<br/>
<div id="fieldset_label">
<label>Address Information</label>
</div>
<fieldset>
<p><span id="streetaddress_error" class="error"></span></p>
<p><label for="streetaddress">Street address</label>
<input type="text" name="Address" id="streetaddress" maxlength="40" "/></p>
<p><span id="suburb_error" class="error"></span></p>
<p><label for="suburb">Suburb/town</label>
<input type="text" name= "Suburb" id="suburb" maxlength="40" /></p>
<p><span id="state_error" class="error"></span></p>
<p><label for="state">State</label>
<select id="state" name="State">
<option value="">Please select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select></p>
<p><span id="postcodr_error" class="error"></span></p>
<p><label for="postcode">Postcode</label>
<input type="text" name= "Postcode" id="postcode" maxlength="4" pattern="\d{4}" placeholder="Postcode"/></p>
</fieldset>
<br/>
<p><span id="email_error" class="error"></span></p>
<p><label for="email">Email</label>
<input type="text" name="Email Address" id="email" /></p>
<p><span id="phonenumber_error" class="error"></span></p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="Phone Number" id="phonenumber" maxlength="12" pattern="[0-9]{8-12}" ></p>
<label>Skill list</label>
<fieldset>
<p><span id="skill_error" class="error"></span></p>
<label for="skill1">Web development languages</label>
<input type="checkbox" id="skill1" name="Skill 1" value="skill"/>
<label for="skill2">Data Management abilities</label>
<input type="checkbox" id="skill2" name="Skill 2" value="skill"/>
<label for="skill3">Others</label>
<input type="checkbox" id="skill3" name="Other" value="skill"/>
<br/>
<br/>
<section>
<label for="comm" style="display:block">Other skillset</label>
<textarea class="comments" id="comm" name="Comments" rows="5" cols="50" placeholder="Other skillsets..."></textarea>
</section>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="align_center">
<p><span id="error_check" class="error"></span></p>
<input type="submit" value="Submit Application"/>
<input type="reset" value="Reset Application form"/>
</div>
</form>
</section>
<br/>
<br/>
<br/>
<br/>
<footer class = "footer_text">
<hr/>
<p>
<strong>©</strong>
<a class="footer_text" href="http://www.swinburne.edu.au/">
Swinburne Universty of Technology
</a>
</p>
<p>  
 
<strong>Done by:</strong> <a class="footer_text" href="mailto:103173691#student.swin.edu.au">
Jordan Siow</a>
</p>
</footer>
JS File:
/* To Validate the Form */
function validate(){
// Initialises the result variable
var result = true;
// Intialises the error tags
var job_id_error = document.getElementById("job_id_error");
job_id_error.innerHTML = "";
var firstname_error = document.getElementById("firstname_error");
firstname_error.innerHTML = "";
var lastname_error = document.getElementById("lastname_error");
lastname_error.innerHTML = "";
var dob_error = document.getElementById("dob_error");
dob_error.innerHTML = "";
var gender_error = document.getElementById("gender_error");
gender_error.innerHTML = "";
var streetaddress_error = document.getElementById("streetaddress_error");
streetaddress_error.innerHTML = "";
var suburb_error = document.getElementById("suburb_error");
suburb_error.innerHTML = "";
var state_error = document.getElementById("state_error");
state_error.innerHTML = "";
var postcode_error = document.getElementById("postcode_error");
postcode_error.innerHTML = "";
var email_error = document.getElementById("email_error");
email_error.innerHTML = "";
var phonenumber_error = document.getElementById("phonenumber_error");
phonenumber_error.innerHTML = "";
var skill_error = document.getElementById("skill_error");
skill_error.innerHTML = ""
// If there is an error in the input it will set the result to false and displays an error message
// To get the variables from the form and will chgeck the given rules
var jobid = document.getElementById("jobid").value;
if (jobid == ""){
job_id_error.innerHTML = "Job Reference Number must not be blank";
result = false;
}
var firstname = document.getElementById("firstname").value;
if (!firstname.match(/^[a-zA-Z]+$/) || firstname.value == ""){
firstname_error.innerHTML = "First name must only contain alphabetic characters";
alert("First name must only contain alphabetic characters")
result = false;
}
var lastname = document.getElementById("lastname").value;
if (!lastname.match(/^[a-zA-Z\-]+$/) || lastname.value == ""){
lastname_error.innerHTML = "Last name must only contain aphabetic characters";
result = false;
}
var dateofbirth = document.getElementById("dateofbirth").value;
if (!dateofbirth.match(/\d{2}\/\d{2}\/\d{4}/)){
dob_error.innerHTML = "Invalid Date of Birth";
result = false;
}
var age = calculate_age(dateofbirth);
if (!isFinite(age) || isNaN(age)) {
dob_error.innerHTML = "Your Date of Birth role is not Available.";
result = false;
}
else if (age < 21 || age > 70) {
dob_error.innerHTML =
"You must be between 21 and 70 years old to apply.";
result = false;
}
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var other = document.getElementById("other").checked;
var rathernotsay = document.getElementById("rathernotsay").checked;
if (!(male || female || other || rathernotsay)) {
gender_error.innerHTML = "Please select a gender.";
result = false;
}
var streetaddress = document.getElementById("streetaddress").value;
if (streetaddress == "") {
streetaddress_error.innerHTML = "You must enter a street address.";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (suburb == "") {
suburb_error.innerHTML = "You must enter a suburb or town";
result = false;
}
var postcode = Number(document.getElementById("postcode").value);
if (postcode == "") {
postcode_error.innerHTML = "You must select a postcode";
result = false;
}
var state = document.getElementById("state").value
if (state == "") {
state_error.innerHTML = "You must select a state";
result = false;
} else {
var tempMsg = validate_postcode(state, postcode);
if (tempMsg != "") {
state_error.innerHTML = tempMsg;
result = false;
}
}
var email = document.getElementById("email").value;
if (email == "") {
email_error.innerHTML = "You must enter an email address";
result = false;
}
var phonenumber = document.getElementById("phonenumber").value;
if (phonenumber == "") {
phonenumber_error.innerHTML = "You must enter a phone number";
result = false;
}
if (result){
storeBooking(firstname, lastname, dateofbirth, male, female, other, rathernotsay, streetaddress, suburb, state, postcode, email, phonnumber)
}
if (!result) {
document.getElementById("error_check").innerHTML = "Please correct all of the errors given above.";
}
return result;
}
/**
* calcualte age from date of birth
*/
function calculate_age(dateofbirth) {
var today = new Date();
var DateOfBirth = new Date(dateofbirth);
// get the difference between the years
var age = today.getFullYear() - DateOfBirth.getFullYear();
// get the difference between the months
var month = today.getMonth() - DateOfBirth.getMonth();
// if the dateofbirth month and day is earlier in the year
if (month < 0 || (month === 0 && today.getDate() < DateOfBirth.getDate())) {
age--; // remove a year
}
return age;
}
function validate_postcode(state, postcode) {
var errMsg = "";
switch (state) {
case "vic":
if (!((postcode >= 3000 && postcode <= 3999) || (postcode >= 8000 && postcode <= 8999))) {
errMsg += "Post Code not in Victoria.";
}
break;
case "nsw":
if (!((postcode >= 1000 && postcode <= 2599) || (postcode >= 2619 && postcode <= 2899) || (postcode >= 2921 && postcode <= 2999))) {
errMsg += "Post Code not in New South Wales.";
}
break;
case "qld":
if (!((postcode >= 4000 && postcode <= 4999) || (postcode >= 9000 && postcode <= 9999))) {
errMsg += "Post Code not in Queensland.";
}
break;
case "nt":
if (!(postcode >= 800 && postcode <= 999)) {
errMsg += "Post Code not in Northern Territory.";
}
break;
case "wa":
if (!(postcode >= 6000 && postcode <= 6999)) {
errMsg += "Post Code not in Western Australia.";
}
break;
case "sa":
if (!(postcode >= 5000 && postcode <= 5999)) {
errMsg += "Post Code not in Southern Australia.";
}
break;
case "tas":
if (!(postcode >= 7000 && postcode <= 7999)) {
errMsg += "Post Code not in Tasmania.";
}
break;
case "act":
if (!((postcode >= 200 && postcode <= 299) || (postcode >= 2600 && postcode <= 2618) || (postcode >= 2900 && postcode <= 2920))) {
errMsg += "Post Code not in Australian Capital Territory.";
}
break;
default:
errMsg = "Post Code not Valid.";
}
return errMsg;
}
/**
* Prefill the form from exisitng session data
*/
function prefill_id() {
var jobId_input = document.getElementById("jobid");
if (localStorage.jobId != undefined) {
// hidden input to submit details
jobId_input.value = localStorage.jobId;
jobId_input.readOnly = true;
} else {
jobId_input.readOnly = false;
}
}
/**
* Prefill the form from exisitng session data
*/
function prefill_form() {
prefill_id();
if (sessionStorage.firstname != undefined) {
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("dateofbirth").value = sessionStorage.dateofbirth;
document.getElementById("streetaddress").value = sessionStorage.streetaddress;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("phonenumber").value = sessionStorage.phonenumber;
switch (sessionStorage.gender) {
case "male":
document.getElementById("male").checked = true;
break;
case "female":
document.getElementById("female").checked = true;
break;
case "other":
document.getElementById("other").checked = true;
break;
case "rathernotsay":
document.getElementById("rathernotsay").checked = true;
break;
}
var skills = sessionStorage.skills;
document.getElementById("skill1").checked = skills.includes("skill1");
document.getElementById("skill2").checked = skills.includes("skill2");
document.getElementById("skill3").checked = skills.includes("skill3");
}
}
/**
* Store Job ID for pre fill in application form
*/
function storeJobId1() {
localStorage.jobId = document.getElementById("job1_id").innerHTML;
}
function storeJobId2() {
localStorage.jobId = document.getElementById("job2_id").innerHTML;
}
/**
* Store values for session
*/
function storeBooking(skill1, skill2, skill3, comm, firstname,
lastname, dateofbirth, streetaddress, suburb, state, postcode, email, phonenumber, male, female, other) {
// store values in sessionStorage
var skill_string = "";
if (skill1) {
skill_string = "skill1";
}
if (skill2) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill2";
}
if (skill3) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill3";
}
sessionStorage.skills = skill_string;
sessionStorage.firstname = firstname;
sessionStorage.lastname = lastname;
sessionStorage.dateofbirth = dateofbirth;
sessionStorage.streetaddress = streetaddress;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = ;
sessionStorage.email = email;
sessionStorage.phonenumber = phonenumber;
sessionStorage.comm = comm;
if (male) {
sessionStorage.gender = "male";
} else if (female) {
sessionStorage.gender = "female";
} else if (other) {
sessionStorage.gender = "other";
} else if (rathernotsay) {
sessionStorage.gender = "rathernotsay";
}
}
/*
This function is called when the browser window loads
it will register functions that will respond to browser events
*/
function init() {
if (document.title == "Available Jobs") {
document.getElementById("job1_apply").onclick = storeJobId1;
document.getElementById("job2_apply").onclick = storeJobId2;
} else if (document.title == "Application Form") {
prefill_form();
// register the event listener to the form
document.getElementById("apply_form").onsubmit = validate;
document.getElementById("apply_form").onreset = function () {
localStorage.clear();
prefill_id();
;}
}
}
window.onload = init;
I think you should check out this article: preventDefault() Event Method
When clicked, you should prevent the default behavior.
<script type="text/JavaScript" src="scripts/apply.js"></script>
Add the above script tag just before closing of body tag, it it best practice.
put a console.log("js file linked"); inside js file to test whether its linked or not.
Feel free to ask if it didn't work...
In the comments you mentioned
my friend told me its got to do with the last line in the js file "window.onload = init();
Your friend is correct - not sure if this is the only relevant thing, but here you are first running the function init() and the return value of that function is being saved into window.onload. Check out this example code:
function init() {
console.log(document.readyState);
}
window.onload = init();
console.log("Window onload is", window.onload);
Here init is run immediately and the return value of init will be saved to window.onload. This prints
loading
apply.js:315 Window onload is null
Instead, you should add a reference to the init function, so that the value of window.onload is your init function itself, not the return value; so the correction would be
function init() {
console.log(document.readyState);
}
window.onload = init;
console.log("Window onload is", window.onload);
// this one prints out
// Window onload is ƒ init() {console.log(document.readyState);}
// apply.js:311 complete
The "document.readyState" is used to check if the document has been loaded and parsed.

Javascript and HTML: doesnt show validation alert message upon clicking submit

I have problem with coding html and js. the alert is not appearing upon submitting and i was following the template entirely. Anyone are able to find what is the problem? im sure my script file is in the same directory and the file is linked after i had tested by using document.write(""). And also what i wish the web page to do is to alert(gErrorMsg).
This is the html part
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="" validate="novalidate">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>
this is the Javascript part
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent;
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList;
}
return selected;
}
This is your issue: you're using some undefined variables. Double check your HTML or if the variable is initialized.
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList; // ERROR: unitList is undefined
}
return selected;
}
Working Demo
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(e){
e.preventDefault(); // Necessary for some reason...
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = ""; //labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n"; // + unitList; // ERROR: unitList is undefined
}
return selected;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>

Concatenation Full Name with Miss Ms in javascript

My Question is that i have one option set which is Gender inside two option Male and Female and one field Fullname. I want that when i select male inside option set the full name is concate with ms and when we select female full name is concate with miss
From what you've said and I understand you could try storing the two in variables and concatenate them like below. However It would be difficult to advise without code snippets.
let title = document.getElementById("title");
let fullName = document.getElementById("fullName");
let titleAndFullName = title + fullName;
Assuming you don't have jQuery restriction you can use:
$("input:radio").click(function() {
console.log($("input[name='Gender']:checked").data('name')+" "+$("input[name='fullname']").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <input type="radio" name="Gender" data-name="Mr" checked="true">Male</label>
<label> <input type="radio" name="Gender" data-name="Ms">Female</label>
<input name="fullname" type="text" />
But if you do need to use pure javascript then you can use:
function check(){
var options = document.getElementsByName("Gender");
var fullname = document.getElementsByName("fullname");
for (var i = 0; i < options.length; i++) {
if (options[i].checked){
console.log(options[i].getAttribute("data-name") + " "+fullname[0].value);
}
}
}
<label> <input type="radio" name="Gender" data-name="Mr" checked="true" onclick="check()">Male</label>
<label> <input type="radio" name="Gender" data-name="Ms" onclick="check()">Female</label>
<input name="fullname" type="text" />
Use something like this.
if (selectedOption == "male") {
document.write("Mr. " + fullname);
} else if (selectedOption == "female") {
document.write("Miss " + fullname);
}
I applied this code and now it's working
==================================================
function GenderValidation(executionContext) {
var formContext = executionContext.getFormContext();
var FullName, gender;
if (formContext.getAttribute("cms_fullname") != null) {
var FullName = formContext.getAttribute("cms_fullname").getValue();
}
if (formContext.getAttribute("cms_gender") != null) {
var gender = formContext.getAttribute("cms_gender").getValue();
}
if (gender == 175650000) {
FullName = "Miss" + ' ' + FullName;
formContext.getAttribute("cms_fullname").setValue(FullName);
} else if (gender == 175650001) {
FullName = "Ms" + ' ' + FullName;
formContext.getAttribute("cms_fullname").setValue(FullName);
}
}

Multiple if condition statements javascript/html

I'm trying to write a condition where:
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
First I tried writing all conditions in the same if...else if statement but it was very confusing so I tried putting them in different if statements and the code for that is below. the problem with this is that the third condition statement is always overridden by the first condition.
Code using html and javascript:
function calculatePrice() {
var tourType;
var payDate;
var returnTrip;
var extra = 0;
var tourCost = 0;
var discount = 0;
for (var i = 1; i <= 3; i++) {
tourType = document.getElementById("ans" + i);
if (tourType.checked == true) {
tourCost += parseFloat(tourType.value);
}
}
if (tourCost == 0 && discount !== 0) {
alert("Please select a Tour type");
return;
}
for (var a = 1; a <= 3; a++) {
payDate = document.getElementById("date" + a);
if (payDate.checked == true) {
discount += parseFloat(payDate.value);
}
}
if (discount == 0 && tourType !== 0) {
alert("Please select a Payment date.");
return;
}
for (var u = 1; u <= 1; u++) {
returnTrip = document.getElementById("return" + u);
if (returnTrip.checked == true) {
extra += parseFloat(returnTrip.value);
}
}
tourCost = tourCost - discount * tourCost + extra
tourCost = parseInt(tourCost)
if (tourCost == 0 && discount == 0) {
alert("Please select a Tour Type and Payment Date.");
return;
} else {
alert("The approximate cost of the holiday is $" + tourCost);
return;
}
}
<h1>Calculator</h1>
<p>Complete the form</p>
<form name="packages">
<p>
Tour type:<br>
<input type="radio" name="tour" id="ans1" value="3900"><label for="ans1">5-day Escape Tour</label><br>
<input type="radio" name="tour" id="ans2" value="5100"><label for="ans2">7-day Splendour Tour</label><br>
<input type="radio" name="tour" id="ans3" value="6600"><label for="ans3">10-day Best Tour</label>
</p>
<p>
Payment date:<br>
<input type="radio" name="dates" id="date1" value="0.1"><label for="date1">Before 1st November 2016</label><br>
<input type="radio" name="dates" id="date2" value="0.07"><label for="date2">Between 1st November and 31st December 2016</label><br>
<input type="radio" name="dates" id="date3" value="0.05"><label for="date3">After 31st December 2016</label>
</p>
<p>
<label for="return1">Click here if you want to include a return airfare from Australia:</label><input type="checkbox" name="return" id="return1" value="900">
</p>
<p>
<input type="submit" value="Calculate" onclick="calculatePrice();"><input type="reset" value="Reset">
</p>
</form>
Basically what I tried to do at first was to see whether any radio buttons were selected and base my if conditions on those. i tried using if (button.selected) but since each radio button has a different id, it was too long and I didn't know how to group them into one variable which I can use.
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
Is best written with the last condition first:
if (!A && !B) { // both are false
display(error_message_3);
} else if (!A) { // if A is false here, B must be true
display(error_message_2);
} else if (!B) { // if B is false here, A must be true
display(error_message_1);
} else { // both are true
display(no_error);
}
The conditions that you asked are :
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
To check if something is true you need to check if it equals to one, not zero.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Travel Agency</title>
<script type="text/javascript">
function calculatePrice() {
var tourType;
var payDate;
var returnTrip;
var extra = 0;
var tourCost = 0;
var discount = 0;
for (var i = 1; i <= 3; i++) {
tourType = document.getElementById("ans" + i);
if (tourType.checked == true) {
tourCost += parseFloat(tourType.value);
}
}
if (tourCost == 1 && discount !== 1) {
alert("Please select a Tour type");
return;
}
for (var a = 1; a <= 3; a++) {
payDate = document.getElementById("date" + a);
if (payDate.checked == true) {
discount += parseFloat(payDate.value);
}
}
if (discount == 1 && tourType !== 1) {
alert("Please select a Payment date.");
return;
}
for (var u = 1; u <= 1; u++) {
returnTrip = document.getElementById("return" + u);
if (returnTrip.checked == true) {
extra += parseFloat(returnTrip.value);
}
}
tourCost = tourCost - discount * tourCost + extra
tourCost = parseInt(tourCost)
if (tourCost !== 1 && discount !== 1) {
alert("Please select a Tour Type and Payment Date.");
return; }
else {
alert("The approximate cost of the holiday is $" + tourCost);
return; }
}
</script>
</head>
<body>
<h1>Calculator</h1>
<p>Complete the form</p>
<form name="packages">
<p>
Tour type:
<br>
<input type="radio" name="tour" id="ans1" value="3900"><label for="ans1">5-day Escape Tour</label>
<br>
<input type="radio" name="tour" id="ans2" value="5100"><label for="ans2">7-day Splendour Tour</label>
<br>
<input type="radio" name="tour" id="ans3" value="6600"><label for="ans3">10-day Best Tour</label>
</p>
<p>
Payment date:
<br>
<input type="radio" name="dates" id="date1" value="0.1"><label for="date1">Before 1st November 2016</label>
<br>
<input type="radio" name="dates" id="date2" value="0.07"><label for="date2">Between 1st November and 31st December 2016</label>
<br>
<input type="radio" name="dates" id="date3" value="0.05"><label for="date3">After 31st December 2016</label>
</p>
<p>
<label for="return1">Click here if you want to include a return airfare from Australia:</label><input type="checkbox" name="return" id="return1" value="900">
</p>
<p>
<input type="submit" value="Calculate" onclick="calculatePrice();"><input type="reset" value="Reset">
</p>
</form>
</body>
</html>
EDIT:
Hey guys, basically what i tried to do at first was to see whether any radio buttons were selected and based my if conditions on those. i tried using if (button.selected) but since each radio button has a different id, it was too long and i didn't know how to group them into one variable which i can use.

Categories