Validation for input value in javascript - javascript

I'm trying to use validation on input field for Employee salary
calculation form by using javascript.
The calculation code works fine, however it can't validate input field before proceeding with calculation.
Here the code.
function validateForm() {
var x = document.forms["myForm"]["employeename"]["employeeno"].value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
}
function paySalary() {
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary );
}
<body>
<form name="myForm" action="" onsubmit="return checkForm(this)" method="post">
<label>Employee Name :</label>
<input id="employeename" value=""><br>
<label>Employee No :</label>
<input id="employeeno" value=""><br>
<label>Rate of pay :</label>
<input id="rate" value=""><br>
<label>Hours Work :</label>
<input id="hours" value=""><br>
<br>
<button id="submit" onclick="paySalary()" >Submit</button>
</form>
<br>
<br>
</body>

The paySalary() function will be executed as soon as you click the submit button and before the form validation. What you can do is writting the validateForm() inside the paySalary() function. If the conditions pass the test then continue..
function validateForm() {
var x = document.getElementById("employeeno").value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
return true;
}
function paySalary() {
// If the form is not valid: stop execution
if(!validateForm()) {
return;
}
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary )
}
<body>
<form name="myForm" action="" onsubmit="return paySalary()" method="post">
<label>Employee Name :</label>
<input id="employeename" value="Bob"><br>
<label>Employee No :</label>
<input id="employeeno"><br>
<label>Rate of pay :</label>
<input id="rate" value="0"><br>
<label>Hours Work :</label>
<input id="hours" value="0"><br>
<br>
<button id="submit">Submit</button>
</form>
<br>
<br>
</body>

Related

Form Submission failed

I have an issue while submitting a form its giving me error that >validateform()is not defined
before it was working.
It is loan application in which I have to send an email once user submit form with correct details and also generate random 4 digit no which will be in email which user will receive
<script src="https://smtpjs.com/v3/smtp.js">
## Heading ##
function validateForm() {
let name = document.forms["myForm"]["fullName"].value;
let email = document.forms["myForm"]["email"].value;
let pan = document.forms["myForm"]["pan"].value;
let lamount = document.forms["myForm"]["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
const mybtn = document.getElementById('btn');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
let number1 = num1.innerText;
let number2 = num2.innerText;
enter code here
mybtn.addEventListener("click", () => {
//
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res == sum_result) {
alert("correct");
}
else {
alert("Incorrect")
}
window.location.reload();
});
if (name == "" || regName.test(name)) {
alert("Name must be filled out");
return false;
}
if (email == "" || !regEmail.test(email)) {
alert("Please enter a valid e-mail address.");
return false;
}
if (pan == "" || !regPan.test(pan)) {
alert("Please enter a valid PAN no.");
return false;
}
//OTP generation
const generateOtp = () =>{
let otp = "";
for(let i=0 ; i < 4 ; i++){
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
console.log("OTP:", generateOtp());
}
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "....",
// To: document.getElementById("email").value,
// From: "....#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
</script>
</head>
<body>
<div class="form-container">
<h1>Loan Application Form</h1>
<form name="myForm" method="post" action="thankyou.html" onsubmit="validateForm();">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span
class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span
class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span
class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span
class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>
You have many issues
You do not have a closing </script> for your <script src="https://smtpjs.com/v3/smtp.js"> and a starting <script> for your code.
Please try to use the snippet editor [<>] and remove the "enter code here" and ## Heading ##
You need to use the submit event and e.preventDefault is stopping the submit. I changed name="myForm" to id="myForm", forms do not need names
You are adding event listeners in the validation.
You were missing the refresh function
Here is what I believe you need
const generateOtp = () => {
let otp = "";
for (let i = 0; i < 4; i++) {
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
document.getElementById('bttn').addEventListener("click", e => {
e.preventDefault();
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
})
document.getElementById("myForm").addEventListener("submit", (e) => {
const form = e.target;
let name = form["fullName"].value;
let email = form["email"].value;
let pan = form["pan"].value;
let lamount = form["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
let number1 = num1.innerText;
let number2 = num2.innerText;
let errors = [];
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res != sum_result) errors.push("Sum not correct");
if (name == "" || regName.test(name)) errors.push("Name must be filled out");
if (email == "" || !regEmail.test(email)) errors.push("Please enter a valid e-mail address.");
if (pan == "" || !regPan.test(pan)) errors.push("Please enter a valid PAN no.");
if (errors) {
alert(errors.join("\n"));
e.preventDefault();
return
}
//OTP generation
console.log("OTP:", generateOtp()); // not sure what you want with this
// sendEmail()
})
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "...",
// To: document.getElementById("email").value,
// From: "...#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
<script src="https://smtpjs.com/v3/smtp.js"></script>
<div class="form-container">
<h1>Loan Application Form</h1>
<form id="myForm" method="post" action="thankyou.html">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>

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.

trying to pull a calculation if a radio button is pressed

What i am trying to do now is have separate calculation when a radio button is highlighted for particular fields... in this case if the radio button is highlightedior "yearly" i want the user input of the text field to be calculated maintFees * 1 = x variable and show that output in maintTimesTwelve.
if not highlighted for "yearly" i want it to be calculated by maintFees * 12. and shown in maintTimesTwelve.
js fiddle:https://jsfiddle.net/ryx4qt0d/
here is the copy of my code
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementByClass("year").checked){
document.getElementById("mantTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>
if (document.getElementByClass("year").checked){ should be if (document.getElementsByClassName("year")[0].checked){ because getElementsByClassName() returns a collection. Can be simplified by using if (document.querySelector(".year").checked){
You had a typo here: document.getElementById("mantTimesTwelve") mant should be maint
Please: Check the console everytime a script doesn't run, it's so easy to find this kind of errors.
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementsByClassName("year")[0].checked){
document.getElementById("maintTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;
}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>

I'm trying to create an temperature conversion program based on radio buttons

My program alerts me when I first start it up, and it won't convert when I click the 'Calculate!' button.
<div id="input">
<form method = "post" action = "hw07.php" name = "form">
Temperature: <input type="text" id="num" name="temperature"> <br />
<input type="radio" name="con" value="far" id="far"> Convert to Fahrenheit
<br />
<input type="radio" name="con" value="cel" id="cel"> Convert to Celcius
<br />
<input type="button" name="submit" value="Calculate!" id="submit">
</form>
</div>
<div id = "results"></div>
window.addEventListener("load", link_events, false);
function link_events() {
var temp = document.getElementById("num");
document.getElementById("submit").onclick = calculate(temp);
}
function calculate(temp) {
if(isNaN(temp)){
alert("Not numeric")
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is" +
Math.round(num-32)*5/9;
}
else if (document.getElementById("cel").checked){
document.getElementById("results").innerHTML = "Temperature is" + Math.round(num*9/5)+32;
}
else
alert("choose a conversion");
return false;
}
I want it to alert me when I click the 'Calculate!' button and not when I start the program. It needs to print the converted value, but it's not even printing anything atm.
You have several problems in your code.
Element.onclick property should be a function, not a function result value
To get proper recalculation each time you press button, you need to get temperature value from input field inside function calculate (Also do not forget to parse it to Number type since it has String type)
The last one is the mysterious num variable which should be temp obviously
All this problem are solved in the code below. Hope this helps.
window.addEventListener("load", link_events, false);
function link_events() {
document.getElementById("submit").onclick = calculate;
}
function calculate() {
var temp = Number(document.getElementById("num").value);
if (isNaN(temp)) {
alert("Not numeric")
return
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is " + Math.round(temp - 32) * 5 / 9;
} else if (document.getElementById("cel").checked) {
document.getElementById("results").innerHTML = "Temperature is " + Math.round(temp * 9 / 5) + 32;
} else {
alert("choose a conversion");
}
return;
}
<div id="input">
<form method = "post" action = "hw07.php" name = "form">
Temperature: <input type="text" id="num" name="temperature"> <br />
<input type="radio" name="con" value="far" id="far"> Convert to Fahrenheit
<br />
<input type="radio" name="con" value="cel" id="cel"> Convert to Celcius
<br />
<input type="button" name="submit" value="Calculate!" id="submit">
</form>
</div>
<div id = "results"></div>
just remove this line
window.addEventListener("load", link_events, false);
and change the link_events function
function link_events() {
var temp = document.getElementById("num");
calculate(temp.value);
}
and add onClick event to button
<input type="button" name="submit" value="Calculate!" id="submit" onclick="link_events()">
also i corected this function
function calculate(temp) {
if (isNaN(temp)) {
alert("Not numeric")
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is" +
Math.round(temp - 32) * 5 / 9;
}
else if (document.getElementById("cel").checked) {
document.getElementById("results").innerHTML = "Temperature is" + Math.round(temp * 9 / 5) + 32;
}
else
alert("choose a conversion");
return false;
}
num is not a variable should be temp in Math.round()

NaN error on form submission [duplicate]

This question already has answers here:
Reading numbers from inputs with JavaScript always returns NaN
(8 answers)
Closed 7 years ago.
I'm attempting to write a simple JavaScript program that calculates the cost of gas based on some parameters from a form. Upon form submission, I get a NaN error inside of the "calculatedMonthlyCost" div.
Can anybody tell me what I'm doing wrong? Is there a better way of doing this?
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
<script>
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
var userCostOfGas = document.forms[0].costOfGas.value;
var userMPG = document.forms[0].vehicleMPG.value;
var userNumMiles = document.forms[0].numMiles.value;
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
</script>
You were getting the values on page load (when they were empty). You just need to get the values inside the onsubmit event listener, and to convert them to Numbers.
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
If you only want 2 decimals, you can change this line:
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
Demo:
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
You save the value of your inputs before the onsubmit method is called. This actually saves a blank value since the variables are set before the user inputs a value and it's not dynamic. The values need to be checked on submit.
document.forms[0].onsubmit = function(e) {
var userCostOfGas = parseInt(document.forms[0].costOfGas.value,10);
var userMPG = parseInt(document.forms[0].vehicleMPG.value,10);
var userNumMiles = parseInt(document.forms[0].numMiles.value,10);
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};

Categories