Cannot figure out why submit button is not working - javascript

The submit button seems to not be running the code from what I can tell, but I'm not sure if that is what is wrong with the code. Spent a long time trying to figure it out, but still have no idea. The forms and everything seem to be right, but when I click submit the only thing that happens is that the form entries disappear and the button seems to just reset the form. In html testers it says that the file is not found so I have no clue on what I should do to debug this particular issue.
<html>
<title>Assignment 5</title>
<body>
<form>
<h2>Step 1: Enter your name, address, etc.</h2>
<formid="Computerparts">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
City: <input type="text" name="city"> State: <input type ="text" name="state"> Zip: <input type="text" name="zipcode"><br>
Phone: <input type="text" name="phonenumber"><br>
Email: <input type="text" name="email"><br>
<h2>Step 2: Select the computer components you want</h2>
CPU: <input type="radio" name="cpu"> Intel 2.0 GHz <input type="radio" name="cpu"> Intel 2.2 GHz <input type="radio" name="cpu"> Intel 3.0 GHz<br>
RAM: <input type="radio" name="ram">SIMM 1 GB <input type="radio" name="ram">SIMM 2 GB <input type="radio" name="ram" value="75">SIMM 4 GB<br>
HDD: <input type="radio" name="hdd"> IDE 60 GB<input type="radio" name="hdd"> IDE 120 GB<input type="radio" name="hdd"> IDE 250 GB<br>
<h2>Step 3: Select the optional Software you want</h2>
<form>
<input type="checkbox" name="software" value="25">Adobe Creative Suite 4<br>
<input type="checkbox" name="software">Microsoft Office 2007<br>
<input type="checkbox" name="software">Symantec Antivirus 2010<br>
<input type="submit" value = "submit" onclick="doSubmit()" /><button type="reset" value="Reset">Clear Entries</button>
</form>
<script>
function doSubmit(){
formTest = document.getElementById("Computerparts");
if(formTest.fname.value == ""){
alert("Name can not be empty");
formTest.name.focus();
return;
}
if(formTest.city.value == ""){
alert("City can not be empty");
formTest.city.focus();
return;
}
if(formTest.state.value.length != 2){
alert("state must be 2 letters");
formTest.state.focus();
return;
}
if(formTest.zip.value.length != 5){
alert("zip must be 5 digits");
formTest.zip.focus();
return;
}
if(formTest.phone.value == ""){
alert("Phone can not be empty");
formTest.phone.focus();
return;
}
if(formTest.email.value == ""){
alert("Email can not be empty");
formTest.email.focus();
return;
}
if(formTest.lname.value == ""){
alert("Last name can not be empty");
formTest.lnamel.focus();
return;
}
var checkcpu = false;
for(var i=0; i<formTest.cpu.length; i++){
if(formTest.cpu[i].checked)
checkcpu = true;
}
if(checkcpu == false){
alert("Must Choose CPU");
return;
}
var pricecpu = 0;
if(formTest.cpu[0].checked)
price = 100;
else if(formTest.cpu[1].checked)
price = 120;
else if(formTest.cpu[2].checked)
price = 150;
var checkram = false;
for(var i=0; i<formTest.ram.length; i++){
if(formTest.ram[i].checked)
checkram = true;
}
if(checkram == false){
alert("Must Choose RAM!");
return;
}
var priceram = 0;
if(formTest.ram[0].checked)
price = 25;
else if(formTest.ram[1].checked)
price = 50;
else if(formTest.ram[2].checked)
price = 75;
var checkhdd = false;
for(var i=0; i<formTest.hdd.length; i++){
if(formTest.hdd[i].checked)
checkhdd = true;
}
if(checkhdd == false){
alert("Must Choose HDD!");
return;
}
var pricehdd = 0;
if(formTest.hdd[0].checked)
price = 60;
else if(formTest.hdd[1].checked)
price = 100;
else if(formTest.hdd[2].checked)
price = 200;
for(var i=0; i<formTest.software.length; i++){
if(formTest.software[i].checked)
price += 25;
}
var price = pricehdd + priceram + pricecpu
alert("Order Submitted , Total: " + price);
}
</script>
</body>
</html>

The way to validate a form is to use the form's submit event and return false if error, true if ok = also where is your action? If no action the page will be submitted to itself:
<form id="computerparts" onsubmit="return doSubmit(this)" action="???">
remove the invalid tag formid and the onclick="doSubmit()" from the submit button and use
function doSubmit(formTest) {
// formTest = document.getElementById("Computerparts"); remove this
if(formTest.fname.value == ""){
alert("Name can not be empty");
formTest.name.focus();
return false; // return false when error
}
.
.
.
return true; // allow submit
}

Related

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 code returning "Not found" when script is called

Updated with entire code for context
My code should run the function when the calculate button is pressed ( in this case, I was testing to see if it would display the alert if I check no radio buttons) but instead the page returns "Not found" message.
Now, I'm totally new at this so it's gone over my head as to what is wrong.
Bonus question: Could I have a hint as to how I make my function look at which buttons are selected and make a calculation from that? Example: If I wanted to selected radio button 1 (having a value of 10) and 3 (having a value of 4) the function would add them together to make 14, and so on for whichever choices you select.
function calculation() {
var cost = 0; //Base cost of flight (one way Economy)
var radioButton; // A radio button
var selection = 0; // The selected radio button, 1 to 6 going down.
for (var i = 1; i <= 6; i++) { // Get the number of the selection (1 to 6)
radioButton = document.getElementById("destination" + i);
if (radioButton.checked == true) {
selection = i;
}
// Give Base cost of flight
if (selection == 1) {
cost = 229
} else if (selection == 2) {
cost = 259
} else if (selection == 3) {
cost = 199
} else if (selection == 4) {
cost = 179
} else if (selection == 5) {
cost = 179
} else if (selection == 6) {
cost = 239
}
// Check if a flight was not selected and prompt
else if (selection == 0) {
alert("Please select a flight.");
}
seating = 0;
for (var x = 1; x <= 3; x++) {
radioButton = document.getElementById("seating" + x);
if (radioButton.checked == true) {
seating = radioButton.id;
}
}
}
}
<h1> Hawkins Airlines Fare Calculator</h1>
<p> Complete the form below to calculate the cost of your flight.</p>
<form>
<p>Route:</p>
<input type="radio" id="destination1"> Hawkins - Riverdale<br>
<input type="radio" id="destination2"> Hawkins - Haddonfield<br>
<input type="radio" id="destination3"> Hawkins - Rockwell<br>
<input type="radio" id="destination4"> Hawkins - Eagleton<br>
<input type="radio" id="destination5"> Hawkins - Pawnee<br>
<input type="radio" id="destination6"> Hawkins - Twin Peaks<br>
<br>
<input type="checkbox" name="appliances" id="return">
<label>Click here if you will be purchasing a return fare </label><br>
<p>Seating class:</p>
<input type="radio" id="seating1"> First seating<br>
<input type="radio" id="seating2"> Business seating<br>
<input type="radio" id="seating3"> Economy seating<br>
<br>
<button onclick="calculation()"> Calculate </button>
<input type="reset" value="Restore Defults">
</form>
I just fixed the javascript code. You should not use class as a variable and there was a missing {} in your first loop
<!DOCTYPE html>
<html>
<head>
</head>
<script>
function calculation() {
var cost = 0; //Base cost of flight (one way Economy)
var radioButton; // A radio button
var selection = 0; // The selected radio button, 1 to 6 going down.
for (var i = 1; i <= 6; i++) {// Get the number of the selection (1 to 6)
radioButton = document.getElementById("destination" + i);
if (radioButton.checked == true) {
selection = i;
}
}
if (selection == 1) {
cost = 229
} else if (selection == 2) {
cost = 259
} else if (selection == 3) {
cost = 199
} else if (selection == 4) {
cost = 179
} else if (selection == 5) {
cost = 179
} else if (selection == 6) {
cost = 239
} else if (selection == 0) {
alert("Please select a flight.");
return false;
}
var seating = 0;
for (var x = 1; x <= 3; x++) {
radioButton = document.getElementById("seating" + x);
if (radioButton.checked == true) {
seating = x;
}
}
var totalcost = 0;
if(seating == 0){
alert("Please select a seat.");
return false;
} else if(seating == 1){
totalcost = cost + (cost * 2);
} else if(seating == 2){
totalcost = cost + (cost * 1.5);
} else if(seating == 3){
totalcost = cost;
}
if(document.getElementById("return").checked){
totalcost = totalcost*2;
}
totalcost = totalcost + cost;
alert("Total cost: "+totalcost);
}
</script>
<body>
<h1> Hawkins Airlines Fare Calculator</h1>
<p> Complete the form below to calculate the cost of your flight.</p>
<form onsubmit="return false;">
<p>Route:</p>
<input type="radio" name="destination" id="destination1"> Hawkins - Riverdale<br>
<input type="radio" name="destination" id="destination2"> Hawkins - Haddonfield<br>
<input type="radio" name="destination" id="destination3"> Hawkins - Rockwell<br>
<input type="radio" name="destination" id="destination4"> Hawkins - Eagleton<br>
<input type="radio" name="destination" id="destination5"> Hawkins - Pawnee<br>
<input type="radio" name="destination" id="destination6"> Hawkins - Twin Peaks<br>
<br>
<input type="checkbox" name="appliances" id="return">
<label>Click here if you will be purchasing a return fare </label><br>
<p>Seating class:</p>
<input type="radio" name="seating" id="seating1"> First seating<br>
<input type="radio" name="seating" id="seating2"> Business seating<br>
<input type="radio" name="seating" id="seating3"> Economy seating<br>
<br>
<button onclick="calculation()"> Calculate </button>
<input type="reset" value="Restore Defults">
</form>
</body>
</html>

javascript - Merging checkboxes into one field in form

I would like to ask for help with function that merge checkboxes into one field. In question Combine checkbox values into string before submitting form I have found one but I would like it to start onsubmit with another function that checks if the form was filled correctlty.
Form:
<form id="formularz_wspolpraca" name="Zapis na poradnik" method="post" target="_top" onsubmit="return SprawdzFormularz(this) && mergeFunction(this)">
<input type="text" id="email" name="email"/>
<input type="text" id="imie" name="imie"/>
<input type="text" id="nazwisko" name="nazwisko"/>
<input type="text" maxlength="12" size="12" id="pole_1" name="pole_1"/>
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3a" value="polecajacy">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3b" value="projektant">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3c" value="instalator">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3d" value="ekspert">
<input type="hidden" name="pole_3" id="pole_3">
<input id="pp" type="checkbox" name="pp" checked=""/>
<input type="submit" value="Wyślij">
</form>
Merge function:
function mergeFuntion(event) {
event.preventDefault();
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}
Check function:
function SprawdzFormularz(f) {
if (f.email.value == "") {
alert("Nie poda\u0142e\u015b/a\u015b adresu e-mail.");
return false;
}
if (((f.email.value.indexOf("#", 1)) == -1) || (f.email.value.indexOf(".", 1)) == -1) {
alert("Poda\u0142e\u015b/a\u015b b\u0142\u0119dny adres e-mail.");
return false;
}
if (f.imie.value == "") {
alert("Wype\u0142nij pole Imi\u0119. ");
return false;
}
if (f.nazwisko.value == "") {
alert("Wype\u0142nij pole Nazwisko. ");
return false;
}
if (f.pole_1.value == "") {
alert("Wype\u0142nij pole Nr telefonu. ");
return false;
}
if ((f.pole_3a.checked == false) && (f.pole_3b.checked == false) && (f.pole_3c.checked == false) && (f.pole_3d.checked == false)) {
alert("Wybierz zakres wsp\u00f3\u0142pracy");
return false;
}
if (f.pp.checked == false) {
alert("Musisz zgodzi\u0107 si\u0119 z Polityk\u0105 Prywatno\u015bci.");
return false;
}
return true;
}
Check function is working without a problem but i can't get merge one to work as well. Can someone point out what am I doing wrong with merge function? I'm quite new to javascript so that could be some rookie mistake. Thanks in advance.
In onsubmit you are running SprawdzFormularz first and it returns true if all the checks pass. This means that it will submit the form, before the merge function is run.
You need to run the merge function inside the check function before returning true so that the form does not submit before you have combined the string and set the necessary value.
function SprawdzFormularz(f) {
// ....
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}

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.

How to check value in input using loop for with onchange using javascript?

How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>

Categories