I'm making a simple client-side, self-grading quiz.
I ask 6 questions and I want to alert the user with their score (keeping things simple). If they leave an answer blank, an alert will appear.
I'm new to javascript and don't really know how to check individual form elements to see if they're empty. I'm also having problems with getting my code to run.
JS
EDIT
function grade() {
var score = 0;
var elt = document.quiz;
// Check to see if no questions were left unanswered.
if elt.question1.value.length == 0 || elt.question2.value.length == 0 ||
elt.question3.value.length == 0 || elt.question4.value.length == 0 ||
elt.question5.value.length == 0 || elt.question6.value.length == 0
{
alert ("Whoops, you're missing an answer!")
}
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked &&
elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false &&
elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
elt.question5 = elt.question5.toLowerCase()
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
elt.question6 = elt.question6.toLowerCase()
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
You have a some significant errors in your markup:
Do not wrap a form element around each question. These should all be in one form element. (Also, each question be in a OL to number the question in series.)
You're not properly closing all of your label's, so they're selecting other elements when you click them (try question 3, first checkbox).
You need the grade() function on the form's submit handler, and it needs to be onsubmit="return grade()", with grade() returning false when it doesn't "pass" to prevent form submission*.
* Note, I set the grade() function to always return false in the example. You would need to add the logic for when it would allow the form to submit.
As far as the Javascript...
You need the elt variable to be equal to your document.quiz (note, I changed the main form to have a name="quiz" in your markup). You can use indexOf() instead of a regex if you just want to have a simple check (regex could check for age as a word, though).
If you just want to make sure a text input is not empty, you can use el.value.length != 0 or el.value != ''.
Also, looking at your grading code, if you want only one to be selected, you could use a radio, unless you want the person taking the quiz to not know if one or more were valid answers. But radio's only allow you to select a single value.
HTML
<h3> Self-Grading Astronomy Quiz </h3>
<form action="" name="quiz" onsubmit="return grade();">
<p>1. According to Kepler the orbit of the earth is a circle with the sun at the center.</p>
<p>
<label><input type="radio" name="question1" value="true" /> True </label>
<label><input type="radio" name="question1" value="false" /> False </label>
</p>
<p>2. Ancient astronomers did consider the heliocentric model of the solar system but rejected it because they could not detect parallax.</p>
<p>
<label><input type="radio" name="question2" value="true" /> True </label>
<label><input type="radio" name="question2" value="false" /> False </label>
</p>
<p>3. The total amount of energy that a star emits is directly related to its:</p>
<p>
<label><input type="checkbox" name="question3" value="1" /> a) surface gravity and magnetic field </label><br/>
<label><input type="checkbox" name="question3" value="2" /> b) radius and temperature </label><br/>
<label><input type="checkbox" name="question3" value="3" /> c) pressure and volume </label><br/>
<label><input type="checkbox" name="question3" value="4" /> d) location and velocity </label>
</p>
<p>4. Stars that live the longest have:</p>
<p>
<label><input type="checkbox" name="question4" value="1" /> a) high mass </label><br/>
<label><input type="checkbox" name="question4" value="2" /> b) high temperature </label><br/>
<label><input type="checkbox" name="question4" value="3" /> c) lots of hydrogen </label><br/>
<label><input type="checkbox" name="question4" value="4" /> d) small mass </label>
</p>
<p>5. A collection of a hundred billion stars, gas, and dust is called a __________.</p>
<p>
<input type='text' id='question5' />
</p>
<p>6. The inverse of the Hubble's constant is a measure of the __________ of the universe.</p>
<p>
<input type='text' id='question6' />
</p>
<p>
<input type='button' onclick='grade()' value='Grade' />
</p>
</form>
Javascript
function grade() {
//**Would I do something like this?
//if(elem.value.length == 0){
// alert("Whoops, looks like you didn't answer a question.")}
var score = 0;
var elt = document.quiz;
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked && elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false && elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
http://jsfiddle.net/BeD3Z/10/
check individual form elements to see if they're empty
You just compare the value to an empty string:
if(elt.question6.value == '') {
alert('Unanswered');
}
You can use jquerys built in validation http://docs.jquery.com/Plugins/validation. It has built in functionality to check for required and to display an error message below the field which is blank.
Related
I am currently working on a fee calculator. Here are the rules for the part of it that I am working on:
There are 9 number input fields, A through I
Input fields D, E, & F are mandatory. The user MUST input a number (greater than 0) in AT LEAST 1 of these 3 input boxes (I have taken care of this aspect already)
The user can only enter a number (greater than 0, no limit) into up to 6 of the 9 inputs, maximum
Something I have already achieved with this app, I have a few check boxes on the page, and the user must select at least 1, up to 5 maximum. Once a user checks 5 of those boxes, they cannot check a 6th. If they un-check one of the 5, they can re-check a different one.
So, I am looking to achieve a similar effect with these number inputs.
Once the user has entered a number (again, greater than 0) in up to 6 of the 9 input fields, they cannot enter something in the one of the 3 remaining inputs. But if they were to remove their input from one of the 6 fields, they should be able to enter a number in one of the 4 other inputs, as now only 5 of them have something entered. Again this number can be any value greater than 0. It could be 10, 10,000 or 100,000, etc. The total values across the inputs doesn't matter, just HOW MANY of the 9 inputs you put a value in (again up to 6 maximum).
I am NOT asking for help with the calculations themselves, nor am I asking for help with the check boxes. I am just wanting some help on the functionality mentioned in the paragraph above.
Also, this must be done in plain vanilla JavaScript, no jQuery.
Any help finding this solution would be much appreciated! Thanks!
Here is the HTML:
<div>
<div>
<label for="Input A">Input A</label>
<input class="entity-input license-input" type="number" name="Input A" value="0" min="0">
</div>
<div>
<label for="Input B">Input B</label>
<input class="entity-input license-input" type="number" name="Input B" value="0" min="0">
</div>
<div>
<label for="Input C">Input C</label>
<input class="entity-input license-input" type="number" name="Input C" value="0" min="0">
</div>
<div>
<label for="Input D">Input D</label>
<input class="entity-input license-input-mandatory" type="number" name="Input D" value="0" min="0">
</div>
<div>
<label for="Input E">Input E</label>
<input class="entity-input license-input-mandatory" type="number" name="Input E" value="0" min="0">
</div>
<div>
<label for="Input F">Input F</label>
<input class="entity-input license-input-mandatory" type="number" name="Input F" value="0" min="0">
</div>
<div>
<label for="Input G">Input G</label>
<input class="entity-input distribution-input" type="number" name="Input G" value="0" min="0">
</div>
<div>
<label for="Input H">Input H</label>
<input class="entity-input distribution-input" type="number" name="Input H" value="0" min="0">
</div>
<div>
<label for="Input I">Input I</label>
<input class="entity-input distribution-input" type="number" name="Input I" value="0" min="0">
</div>
</div>
And here is the JavaScript I have so far:
// Select all elements with class of entity-input
const ENTITY_INPUTS = document.querySelectorAll('.entity-input');
// Prevent user from entering a number on 7th number input (cannot fill in more than 6)
ENTITY_INPUTS.forEach((input) => {
const MAX = 6;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (unchangedInputs.length !== []) {
console.log(`The number of inputs with a value still at zero is ${unchangedInputs.length}`);
}
});
// Count the number of inputs with data-changed set to true - can't be more than 6
input.addEventListener('focus', () => {
let changedInputs = document.querySelectorAll('[data-changed="true"]');
console.log(`The number of inputs with a value more than zero is ${changedInputs.length}`);
if (changedInputs.length == MAX && input.value > 0) {
console.log(`You may change this element`);
} else if (changedInputs.length == MAX) {
console.log(`You can't enter any more numbers!`);
}
});
});
EDIT: I was able to solve this after some slight modifications to my HTML and JS.
I gave all 9 inputs the attribute data-changed="false" by default, instead of having it assigned dynamically based on user input. And similar to #7iiBob's answer, I put everything into blur, and I got the effect I needed:
ENTITY_INPUTS.forEach((input) => {
const REMAINING_INPUTS = 3;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
// upon leaving, check number of elements still with data-changed set to false
// if the number of elements is equal to 3, set them to disabled
// else, leave them alone (set disabled to false)
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (unchangedInputs.length == REMAINING_INPUTS) {
unchangedInputs.forEach((input) => {
input.disabled = true;
});
} else {
unchangedInputs.forEach((input) => {
input.disabled = false;
});
}
});
});
You look pretty darn close to having this solved.
Why not put everything into blur?
// Select all elements with class of entity-input
const ENTITY_INPUTS = document.querySelectorAll('.entity-input');
// Prevent user from entering a number on 7th number input (cannot fill in more than 6)
ENTITY_INPUTS.forEach(input => {
const MAX = 6;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
let changedInputs = document.querySelectorAll('[data-changed="true"]');
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (changedInputs.length == MAX) {
unchangedInputs.forEach(inputToDisable =>
inputToDisable.setAttribute('disabled', 'true')
);
} else if (changedInputs.length < MAX) {
unchangedInputs.forEach(inputToEnable =>
inputToEnable.setAttribute('disabled', 'false')
);
}
});
});
This is the logic.
Implant on checkboxes:
let inputCheckboxesLength = 0; // initial counter to 0
const inputCheckboxes = document.querySelectorAll('#inputCheck input'); // target the checkboxes
for (var i=0; i < inputCheckboxes.length; i++) { // iterate checkboxes
inputCheckboxes[i].addEventListener('change', function() { // listen to changne event:
if (this.checked) { // if one of the checkboxes selected:
++inputCheckboxesLength; // increase the count
if (inputCheckboxesLength === 6) { // if the count more then 5 (equal to 6)
alert ('You cannot check more then 5 checkboxes!'); // alert error message
inputCheckboxesLength = 5; // change the count back to 5
this.checked = false; // remove the checked for the last checkbox
}
}
else {
--inputCheckboxesLength // decrease the count - will tirgger when user remove check-mark from checkbox
}
});
}
<fieldset id="inputCheck">
<label for="check1">1<input type="checkbox" id="check1" /></label>
<label for="check2">2<input type="checkbox" id="check2" /></label>
<label for="check3">3<input type="checkbox" id="check3" /></label>
<label for="check4">4<input type="checkbox" id="check4" /></label>
<label for="check5">5<input type="checkbox" id="check5" /></label>
<label for="check6">6<input type="checkbox" id="check6" /></label>
<label for="check7">7<input type="checkbox" id="check7" /></label>
<label for="check8">8<input type="checkbox" id="check8" /></label>
</fieldset>
Implant on inputs:
let inputNumberLength = 0; // initial counter to 0
const inputNumbers = document.querySelectorAll('#inputNumber input'); // target the inputs
for (var i=0; i < inputNumbers.length; i++) { // iterate inputs
inputNumbers[i].addEventListener('change', function() { // listen to changne event:
if (this.value.length > 0) {
++inputNumberLength; // increase the count
if (inputNumberLength === 6) { // if the count more then 5 (equal to 6)
alert ('You cannot put more then 5 values!'); // alert error message
inputNumberLength = 5; // change the count back to 5
this.value = ''; // remove the value for the last input
}
}
else {
--inputNumberLength // decrease the count - will tirgger when user remove check-mark from checkbox
}
});
}
<fieldset id="inputNumber">
<label for="a"><input type="number" id="a" /></label>
<label for="b"><input type="number" id="b" /></label>
<label for="c"><input type="number" id="c" /></label>
<label for="d"><input type="number" id="d" /></label>
<label for="e"><input type="number" id="e" /></label>
<label for="f"><input type="number" id="f" /></label>
<label for="g"><input type="number" id="g" /></label>
<label for="h"><input type="number" id="h" /></label>
<label for="i"><input type="number" id="i" /></label>
</fieldset>
I'm using javascript for the first time and am trying to pass variables to another page via a cookie. However it doesn't appear to be working. Right now I'm just trying to check the cookie value using an alert box. I've looked but haven't been able to find anything that can help me figure out what's going wrong. I was originally trying to implement the solution from this page: How to use JavaScript to fill a form on another page
Any help is appreciated.
My code for the first page is:
<!DOCTYPE html>
<html lang="en">
<!--Matt Proctor -->
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet/less" type="text/css" href="dealership.less">
<script src="less.js" type="text/javascript"></script>
</head>
<body>
<script>
//validate name
function checkName() {
var lastN = document.getElementById('lName').value;
var firstN = document.getElementById('fName').value;
if (lastN == "" || firstN == "" || (/[^A-Za-z]/.test(lastN)) || (/[^A-Za-z]/.test(firstN))) {
window.alert("Please enter ONLY alphabetical characters for First Name AND Last Name");
return false;
}
else{
return true;
}
}
//check if q1 answered
function checkQ1() {
if (document.getElementById('timeButton1').checked == false
&& document.getElementById('timeButton2').checked == false
&& document.getElementById('timeButton3').checked == false
&& document.getElementById('timeButton4').checked == false
&& document.getElementById('timeButton5').checked == false) {
window.alert("Please answer question 1");
return false;
}
else{
return true;
}
}
//check if q2 answered
function checkQ2() {
if (document.getElementById('vehicleButton1').checked == false
&& document.getElementById('vehicleButton2').checked == false
&& document.getElementById('vehicleButton3').checked == false
&& document.getElementById('vehicleButton4').checked == false
&& document.getElementById('vehicleButton5').checked == false
&& document.getElementById('vehicleButton6').checked == false
&& document.getElementById('vehicleButton7').checked == false
&& document.getElementById('vehicleButton8').checked == false
&& document.getElementById('vehicleButton9').checked == false
&& document.getElementById('vehicleButton10').checked == false
&& document.getElementById('vehicleButton11').checked == false) {
window.alert("Please answer question 2");
return false;
}
else{
return true;
}
}
//validate q3
function checkQ3() {
var min = document.getElementById('minPriceText').value;
var max = document.getElementById('maxPriceText').value;
if (min == "" || (/[^0-9]/.test(min)) || max == "" || (/[^0-9]/.test(max))) {
window.alert("Please enter a numerical value for both the minimum price and maximum price");
return false;
}
else{
return true;
}
}
//check q4 answered
function checkQ4() {
if (document.getElementById('problemsNo').checked == false
&& document.getElementById('problemsYes').checked == false) {
window.alert("Please answer question 4");
return false;
}
else {
return true;
}
}
//check q5 answered
function checkQ5() {
if (document.getElementById('cleanNo').checked == false
&& document.getElementById('cleanYes').checked == false) {
window.alert("Please answer question 5")
return false;
}
else {
return true
}
}
//check q6 answered
function checkQ6() {
if (document.getElementById('gasNo').checked == false
&& document.getElementById('gasYes').checked == false) {
window.alert("Please answer question 6")
return false;
}
else {
return true;
}
}
//check q7 answered
function checkQ7() {
if (document.getElementById('experience1').checked == false
&& document.getElementById('experience2').checked == false
&& document.getElementById('experience3').checked == false
&& document.getElementById('experience4').checked == false
&& document.getElementById('experience5').checked == false
&& document.getElementById('experience6').checked == false
&& document.getElementById('experience7').checked == false
&& document.getElementById('experience8').checked == false
&& document.getElementById('experience9').checked == false
&& document.getElementById('experience10').checked == false) {
window.alert("Please answer question 7")
return false;
}
else {
return true;
}
}
//check if all data correct, and then attempt to pass to another webpage via cookie.
function checkAndPass() {
var nameCorrect, q1Correct, q2Correct, q3Correect, q4Correct, q5Correct, q6Correct, q7Correct;
nameCorrect = checkName();
q1Correct = checkQ1();
q2Correct = checkQ2();
q3Correct = checkQ3();
q4Correct = checkQ4();
q5Correct = checkQ5();
q6Correct = checkQ6();
q7Correct = checkQ7();
if(nameCorrect==true &&
q1Correct==true &&
q2Correct==true &&
q3Correct==true &&
q4Correct==true &&
q5Correct==true &&
q6Correct==true &&
q7Correct==true) {
var name = document.getElementById('fName').value + " " + document.getElementById('lName').value;
var quest1 = document.querySelector('input[name = "Q1"]:checked').value;
var quest2 = document.querySelector('input[name = "Q2"]:checked').value;
var quest3 = document.getElementById('minPriceText').value + "-" + document.getElementById('maxPriceText').value;
var quest4 = document.querySelector('input[name = "Q4"]:checked').value;
var quest5 = document.querySelector('input[name = "Q5"]:checked').value;
var quest6 = document.querySelector('input[name = "Q6"]:checked').value;
var quest7 = document.querySelector('input[name = "Q7"]:checked').value;
var commentline = document.getElementById('comments').value;
document.cookie=name + "," + quest1 + "/" + quest2 + "/" + quest3 + "/" + quest4 + "/" + quest5 "/" + quest6 + "/" + quest7 + "/" + commentline + "; path=/lab5summary.html";
newSummary();
}
}
function newSummary() {
window.open('lab5summary.html',
'_blank');
}
</script>
<img class="displaycenter" src="AcuraLogo.png" alt="Acura Logo">
<h1 align ="center">After Purchase Customer Survey</h1>
<div class="customer">
<h4>Customer Information</h4>
<br>
<br>
First name:<br>
<input id="fName" type="text" name="firstname" value="">
<br>
Last name:<br>
<input id="lName" type="text" name="lastname" value="">
</div>
<br><br>
<!--Question 1 asking about how long a customer had to wait before an employee assisted them-->
<div class="border">
<p> Q1: What was your approximate wait time before an associate was available to assist you?</p>
<input id="timeButton1" type="radio" class ="larger" name="Q1" value=".25">15 minutes or less.
<input id="timeButton2" type="radio" class ="larger" name="Q1" value=".5">30 minutes.
<input id="timeButton3" type="radio" class ="larger" name="Q1" value=".75">45 minutes.
<input id="timeButton4" type="radio" class ="larger" name="Q1" value="1">1 hour.
<input id="timeButton5" type="radio" class ="larger" name="Q1" value="1.5">1 and 1/2 hours or more.
<p> Q2: What kind of vehicle(s) were you looking for?</p>
<input id="vehicleButton1" type="checkbox" class ="larger" name="Q2" value="Sedan"> Sedan
<input id="vehicleButton2" type="checkbox" class ="larger" name="Q2" value="SUV/Crossover"> SVU/Crossover
<input id="vehicleButton3" type="checkbox" class ="larger" name="Q2" value="Convertible"> Convertible
<input id="vehicleButton4" type="checkbox" class ="larger" name="Q2" value="Coupe"> Coupe
<input id="vehicleButton5" type="checkbox" class ="larger" name="Q2" value="Hatchback"> Sedan
<input id="vehicleButton6" type="checkbox" class ="larger" name="Q2" value="Hybrid/Electric"> Hybrid/Electric
<input id="vehicleButton7" type="checkbox" class ="larger" name="Q2" value="Luxury"> Luxury
<input id="vehicleButton8" type="checkbox" class ="larger" name="Q2" value="Van/Minivan"> Van/Minivan
<input id="vehicleButton9" type="checkbox" class ="larger" name="Q2" value="Truck"> Truck
<input id="vehicleButton10" type="checkbox" class ="larger" name="Q2" value="Wagon"> Wagon
<input id="vehicleButton11" type="checkbox" class ="larger" name="Q2" value="AWD/4WD"> AWD/4WD
<p> Q3: What price range were looking for in a vehicle? </p>
Minimum: $
<input id="minPriceText" type="text" name="minprice" value="">
Maximum: $
<input id="maxPriceText" type="text" name="minprice" value="">
<p> Q4: Did the vehicle(s) purchased have any problems?</p>
<input id="problemsNo" type="radio" class ="larger" name="Q4" value="Yes">Yes
<input id="problemsYes" type="radio" class ="larger" name="Q4" value="No">No
<p> Q5: Was the interior of the vehicle clean? </p>
<input id="cleanYes" type="radio" class ="larger" name="Q5" value="Yes">Yes
<input id="cleanNo" type="radio" class ="larger" name="Q5" value="No">No
<p> Q6: Did the vehicle come with a full tank of gas? </p>
<input id="gasYes" type="radio" class ="larger" name="Q6" value="Yes">Yes
<input id="gasNo" type="radio" class ="larger" name="Q6" value="No">No
<p> Q7: On the scale from 1 to 10, 1 being extremely unpleasant and
10 being absolutely perfect, how would you rate your overall experience? </p>
<input id="experience1" type="radio" class ="larger" name="Q7" value="1">1
<input id="experience2" type="radio" class ="larger" name="Q7" value="2">2
<input id="experience3" type="radio" class ="larger" name="Q7" value="3">3
<input id="experience4" type="radio" class ="larger" name="Q7" value="4">4
<input id="experience5" type="radio" class ="larger" name="Q7" value="5">5
<input id="experience6" type="radio" class ="larger" name="Q7" value="6">6
<input id="experience7" type="radio" class ="larger" name="Q7" value="7">7
<input id="experience8" type="radio" class ="larger" name="Q7" value="8">8
<input id="experience9" type="radio" class ="larger" name="Q7" value="9">9
<input id="experience10" type="radio" class ="larger" name="Q7" value="10">10
<p> Finally please feel free to leave any other comments about your purchase/purchase-process below: </p>
<input id="comments" type="textbox" name="comments" value="" size="100">
</div>
<br>
<br>
<input onclick="checkAndPass()" id="submitButton" class="button1" type="submit" value="Submit">
</body>
</html>
The code of the page I'm passing to is:
<!DOCTYPE html>
<html lang="en">
<!--Matt Proctor -->
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet/less" type="text/css" href="dealership.less">
<script src="less.js" type="text/javascript"></script>
</head>
<body>
<script>
var COOKIES = {};
var cookieStr=document.cookie;
window.alert("Cookie: " + cookieStr);
</script>
<img class="displaycenter" src="AcuraLogo.png" alt="Acura Logo">
<h1 align ="center">After Purchase Customer Survey Summary</h1>
<div class="border">
<p> Q1: What was your approximate wait time before an associate was available to assist you?</p>
<p> Q2: What kind of vehicle(s) were you looking for?</p>
<p> Q3: What price range were looking for in a vehicle? </p>
Minimum: $
Maximum:
<p> Q4: Did the vehicle(s) purchased have any problems?</p>
<p> Q5: Was the interior of the vehicle clean? </p>
<p> Q6: Did the vehicle come with a full tank of gas? </p>
<p> Q7: On the scale from 1 to 10, 1 being extremely unpleasant and
10 being absolutely perfect, how would you rate your overall experience? </p>
<p> Finally please feel free to leave any other comments about your purchase/purchase-process below: </p>
</div>
</body>
</html>
Also, for some reason firefox web console seems to think I need to place a semi-colon here in the first page after quest5:
document.cookie=name + "," + quest1 + "/" + quest2 + "/" + quest3 + "/" + quest4 + "/" + quest5 "/" + quest6 + "/" + quest7 + "/" + commentline + "; path=/lab5summary.html";
As a final note, I can only use javascript for this, not jQuery or PHP.
In your example is missing a plus sign:
+ quest5+"/" + quest6
Cookies are bound by a domain, so if you open from your file system (e.g file://index.html), it won't work.
If you are on modern browsers, I suggest you use localStorage and sessionStorage.
sessionStorage lasts as long as the page is open and localStorage until the browser's cache be cleaned.
You can also use store.js
Store.js
And you also probably want to expurge your code by using objects and arrays for ids and variables.
I am using this function to validate a form. It is triggered 'onsubmit' when form is submitted. isPresentCond2 determines if 'condition 2' is present (some forms on the site do not have a condition 2 input). If the input is found to be null or an empty string it alerts the user and triggers a button. It is working on all browsers except safari.
In Safari it will return x as false and trigger a confirm "please enter x"
No error messages.
function validateForm() {
var isPresentCond2 = document.forms["form1"]["condition2"],
x = document.forms["form1"]["condition1"].value,
y,
z = document.forms["form1"]["condition3"].value;
if (x == null || x == "") {
confirm("Please enter a condition1 value");
$("#Button1").trigger("click");
return false;
}
if (isPresentCond2) {
y = document.forms["form1"]["condition2"].value;
if (y == null || y == "") {
confirm("Please enter a condition2 value");
$("#Button2").trigger("click");
return false;
}
}
if (z == null || z == "") {
confirm("Please enter a condition3 value");
$("#button3").trigger("click");
return true;
}
}
Sample Form:
<form name="form1" action="results.php" onsubmit="return validateForm(this)" method="post>
<input type="radio" name="condition1" value="1">
<input type="radio" name="condition1" value="2">
<input type="radio" name="condition1" value="3">
<input type="radio" name="condition2" value="1">
<input type="radio" name="condition2" value="2">
<input type="radio" name="condition2" value="3">
<input type="radio" name="condition3" value="1">
<input type="radio" name="condition3" value="2">
<input type="radio" name="condition3" value="3">
<button type="submit" class="btn-xl btn-success btn-block">See Results <span class="glyphicon glyphicon-circle-arrow-right"></span></button>
Should the if statements look more like this?
if (!X) ....
Is there an obvious reason that this function that would be causing problems with Safari?
Thanks.
So I learning jQuery atm, and have to make a Loan calculator based on choices, as well as validate enteries, then output a result.
l wanted to make sure you guys knew what i was trying to do, so i have here a flow chart of what is supposed to happen:
http://i59.tinypic.com/8z02sh.jpg
that shows what is supposed to be happening. Problem is i dont know how to do this is Jquery. The radio button selector i found online (through another question on here) seems weird and i dont know how to use it. I could do this using javascript, but then i wouldn't be learning anything. So here's my code so far.
Also, im getting an error on line 14 of my JS (line 14 in JSfiddle), and i cant figure out what it is.
JSfiddle: http://jsfiddle.net/keup5vaw/1/
HTML:
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
and JS -
$('#check').click(function () {
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid) {
var salary = Number($('#salary').val());
if (salary < 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
} else if {
$('#message').html("Loan Denied.")
}
}
} else(salary >= 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
if ($('input[name=job1]:checked').length > 0) $('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate({
rules: {
salary: {
required: true,
digits: true,
range: [1, 1000000]
}
}
});
As per usual, thank you ahead of time, you guys are awesome.
Edit: Updated after Mottie helped out (thank you!), Still not seeing what line 14 is doing wrong, but changed the else to else if, and used the tidy up.
If your having problems with the checking if a radio is checked you can use this its a lot cleaner than what you are currently using and is more intuitive.
if($("#id1").is(":checked")){
// do something
}else if($("#id2").is(":checked")){
// do something else
}
Hope this helps.
Formatting your javascript is really important to catch those type of syntax error for your self. As #Mottie said use some kind of javascript formatter to fix those issues.Tidy Up,
http://jsbeautifier.org/ are better place to start up with. Here is the correct code
$('#check').click(function()
{
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid)
{
var salary = Number($('#salary').val());
if (salary < 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
$('#message').html("Loan Denied.")
}
}
else
{
$('#message').html("Loan Denied.")
}
}
else if (salary >= 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
if ($('input[name=job1]:checked').length > 0)
$('#message').html("Loan Approved.")
}
}else
{
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate(
{
rules:
{
salary:
{
required: true,
digits: true,
range: [1, 1000000]
}
}
});
modified your jquery
http://jsfiddle.net/cvynLaqf/
$('#check').click(function(){
var salary;
//var isValid = $('#salaryForm').validate().form();
var isValid = true;
// if validation passes, display a message
if (isValid){
var salary = Number($('#salary').val());
if (salary < 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//if over 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
else {
$('#message').html("Loan Denied.");}
}
else {
$('#message').html("Loan Denied.");
}
} else if( salary >= 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//over 600 do this
$('#message').html("Loan Approved.");}
else {
//under 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
}
else {
$('#message').html("Loan Denied.");}
}
}
});
// form validation
//$('#salaryForm').validate({
// rules: {
// salary: {
// required: true,
// digits: true,
// range: [1, 1000000]
// }
// }
//});
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
i commented out your validation because im getting an error on my part
Despite an answer already being accepted, I figured I'd post an updated script since you're just beginning to learn jQuery to maybe help you improve further.
You're way over complicating the conditionals (if/else statements) for starters.
Break it down based on the behavior you would like to accomplish and word out the functionality the same way too.
Makes it a lot easier to read if you (or someone else) needs to look at it again in 6 months.
Has Good Credit?
Has Standing Job?
Is Loan Approved?
Has Good Salary?
Here's the rewritten functional fiddle.
http://jsfiddle.net/q3xpsLmL/
I also merged the individual forms to clean up a little. I changed the validation to HTML 5's required, type=number, min and max since the .validate() plugin was not in the fiddle.
Relying on HTML 5 and jQuery submit() event to validate the form.
Some more info on HTML 5 validation and pattern if you're interested:
http://www.w3.org/html/wg/drafts/html/master/forms.html#the-pattern-attribute
You can even style it using css :valid and :invalid pseudo-classes
I had trouble interpreting your logic for a applicant with a good salary. So I set it to approve if the person has a good salary and either good credit or a standing job.
If you have questions on it just add a comment.
HTML
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0);">
<label for="salary">Enter your annual salary</label>
<input id="salary" type="number" name="salary" min="0" max="1000000000" required>
<p>Please select your Credit Score</p>
<p>
<input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label>
</p>
<p>
<input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label>
</p>
<p>How long have you worked at your current job?</p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label>
<br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label>
<br>
<button type="submit" id="check" name="check">Check</button>
</form>
<div id="message"></div>
JavaScript
//use strict to ensure variables are defined and to prevent collisions
"use strict";
//define DOM elements so events do not need refind the element.
var salryForm = $('#salaryForm');
var salaryElement = $('#salary');
var messageElement = $('#message');
var radioButtons = $('input[type=radio]');
var goodCredit = radioButtons.filter('[name=radio][value=over1]');
var standingJob = radioButtons.filter('[name=job][value=0]');
var isLoanApproved = function(salary){
//always be pecimistic and decline unless all conditions are met
var result = false;
var hasGoodCredit = goodCredit.is(':checked');
var hasStandingJob = standingJob.is(':checked');
var hasGoodSalary = (salary >= 40000);
/*
* if applicant doesn't have a good salary
* they have to have good credit and standing job to be approved
*/
if (!hasGoodSalary && hasGoodCredit && hasStandingJob) {
result = true;
/**
* otherwise if applicant does have a good salary
* they only need to have either good credit or standing job to be approved
*/
} else if(hasGoodSalary && (hasGoodCredit || hasStandingJob)) {
result = true;
}
return result;
};
/**
* track on submit rather than click so you can catch "<enter>" key presses as well
*/
salryForm.submit(function(e) {
var salary = salaryElement.val();
messageElement.html('Loan ' + (isLoanApproved(salary) ? 'Approved' : 'Denied'));
return false;
});
I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}