I'm not sure what I'm doing wrong here. It says that my variables are not defined, but I did that at the top of the js file. I think all my logic is correct, but something is not right somewhere I haven't been able to figure out what it is. I'm just adding more text here so it will let me edit this question with updated coded. Delete this last bit as needed. Thanks.
function calculate() {
document.getElementById("cost").innerHTML = "Cost: "
var cost = Number(document.getElementById("type").value);
var years = Number(document.getElementById("years").value);
if (years > 1) {
var discount = cost * 0.20
cost -= discount ; // 20%
document.getElementById("cost").innerHTML += cost;
} else {
document.getElementById("cost").innerHTML += cost;
}
return false;
}
I made two changes and it runs without error:
var cost = parseInt(document.getElementById("cost).value);
Should have another " after cost, and:
if (type && type.value && years && (years > 0)) {
should be years.value > 0
Then change the switch to:
switch (type.value) {
and the cases to:
case 'basic':
case 'premium':
etc.
function calculate() {
// Be strict:
'use strict';
// Variable to store the total cost:
var cost;
// Get a reference to the form elements:
var type = document.getElementById('type');
var years = document.getElementById('years');
// TODO Convert the year to a number:
// Check for valid data:
if (type && type.value && years && (years.value > 0)) {
// TODO Add a switch statement to determine the base cost using the value of "type"
switch (type.value) {
case 'basic':
window.console.log("Basic - $10.00");
break;
case 'premium':
window.console.log("Premium - $15.00");
break;
case 'gold':
window.console.log("Gold - $20.00");
break;
case 'platinum':
window.console.log("Platinum - $25.00");
}
// TODO Update cost to factor in the number of years:
var cost = parseInt(document.getElementById("cost").value);
// Discount multiple years:
if (years > 1) {
cost -= (cost*20); // 20%
}
// TODO update the value property of 'costElement' to the calculated cost
var costElement = document.getElementById('cost');
} else { // Show an error:
document.getElementById('cost').value = 'Please enter valid values.';
}
// Return false to prevent submission:
return false;
}
function init() {
'use strict';
// call a function named calculate() when form submitted
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;
<!DOCTYPE html>
<html>
<head>
<title>58123301</title>
<head>
<body>
<div>
<form action="" method="post" id="theForm">
<fieldset><legend>Create Your Membership</legend>
<div><label for="type">Type</label> <select name="type" id="type" required>
<option value="basic">Basic - $10.00</option>
<option value="premium">Premium - $15.00</option>
<option value="gold">Gold - $20.00</option>
<option value="platinum">Platinum - $25.00</option>
</select></div>
<div><label for="years">Years</label><input type="number" name="years" id="years" min="1" required></div>
<div><label for="cost">Cost</label><input type="text" name="cost" id="cost" disabled></div>
<input type="submit" value="Calculate" id="submit">
</fieldset>
</form>
</div>
<script type="text/javascript" src="58123301.js"></script>
</body>
</html>
I worked on your code and I fixed a few issues, hope this will help you:
function calculate() {
document.getElementById("cost").innerHTML = "Cost: "
var cost = Number(document.getElementById("type").value);
var years = Number(document.getElementById("years").value);
if (years > 1) {
var discount = cost * 0.20
cost -= discount ; // 20%
document.getElementById("cost").innerHTML += cost;
} else {
document.getElementById("cost").innerHTML += cost;
}
return false;
}
<form action="" method="post" id="theForm">
<fieldset>
<legend>Create Your Membership</legend>
<div>
<label for="type">Type</label>
<select name="type" id="type" required>
<option value="10.00">Basic - $10.00</option>
<option value="15.00">Premium - $15.00</option>
<option value="20.00">Gold - $20.00</option>
<option value="25.00">Platinum - $25.00</option>
</select>
</div>
<div>
<label for="years">Years</label
><input type="number" name="years" id="years" min="1" required />
</div>
<div>
<p id="cost">Cost: </p>
</div>
<input type="button" value="calculate" id="submit" onclick="calculate()"/>
</fieldset>
</form>
Related
My find matches function does not seem to be working.
I want to get an array ([]) element by id and do comparisons with it.
The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".
I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.
<html>
<head>
<script>
var records = [];
function calculateAge()
{
var dob = document.getElementById('dob').value;
var dobInput = new Date(dob);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var birthyear = dobInput.getFullYear();
var birthmonth = dobInput.getMonth();
var birthday = dobInput.getDate();
var bYear = year - birthyear;
var bMonth = month - birthmonth;
var bDay = day - birthday;
if (bYear < 18 || bYear > 75)
{
alert("Age cannot be less than 18 or greater than 75");
return false;
}else{
document.getElementById("age").value = bYear + "years old";
}
//document.getElementById("age").value = bYear + "years old";
}
function showAll()
{
show = document.getElementById("showallpersons").innerHTML=records;
show.value = records.join("\n");
}
(window.onload = () => {
var findmatches=document.getElementById('findmatches');
if(findmatches){
findmatches.addEventListener('click', findMatches, false);
}
function findMatches(e)
{
e.preventDefault();
for(var counter=0; counter<records.length; counter++)
{
var currposn = records[counter].value;
var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
show.value = currposn.join("\n");
do
{
//From here
var randpson = Math.random() * records.length;
randpson = Math.floor(randpson); //To here works, I know that for sure
//I'm not sure if the conditions for the if statements are correct
if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
{
if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
{
var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
//display.value = "Matched to: " + randpson.fname + randpson.lname;
break;
}
}
} while(counter < 10){
//var newDisplay = document.getElementById("showallmatches").innerHTML= null;
}
//console.log(findMatches());
}
}
})()
(window.onload = () => {
var submit = document.getElementById('submit');
if(submit){
submit.addEventListener('click', addnew, false);
}
function addnew(event)
{
//Prevents default submit event
event.preventDefault();
//Accept values entered in form
var fname = document.getElementById('fname').value;
var mname = document.getElementById('mname').value;
var lname= document.getElementById('lname').value;
var dob= document.getElementById('dob').value;
var gender = document.forms['Information']['gender'].value;
var age = document.getElementById('age').value;
parseInt(age);
var bodyType = document.getElementById('Body Type').value;
var occu= document.getElementById('occu').value;
var height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert("A first name is required");
return false;
}
if(mname==null || mname=="")
{
alert("A middle initial is required");
return false;
}
if (lname==null || lname=="")
{
alert("A last name is required");
return false;
}
if(dob==null || dob=="")
{
alert("A DOB is required");
return false;
}
if (gender == "")
{
alert("Please select a gender");
return false;
}
if(height <= 170 || height >= 200)
{
alert("A height between 170, not less and 200, not more is required");
return false;
}
if(bodyType==null || bodyType==""){
alert("Please choose a body type");
return false;
}
if(occu==null || occu=="")
{
alert("Please enter an occupation");
return false;
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(gender);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
document.getElementById("Information").reset();
}
})()
</script>
</head>
<body>
<div class="wrapper">
<header class="page-header">
<nav>
<button class="cta-contact">Contact Us</button>
</nav>
</header>
</div>
<div class="space">
<h1>
<marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
</h1>
</div>
<div class="container">
<form name="Information" id="Information">
<fieldset>
<legend>Personal Information</legend>
First Name:
<input id="fname" type="text" size=40 placeholder='First Name' minlength=4 maxlength=40 required />
<br/><br/>
Middle Initial:
<input id="mname" type="text" size=3 placeholder='M Intial' maxlength=1 required />
<br/><br/>
Last Name:
<input id="lname" type="text" size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
<br/><br/>
Date of Birth
<input id="dob" type="date" onchange="calculateAge()"/>
<br/><br/>
Gender:
<input id="male" type="radio" value='M' name="gender" required/> Male
<input id="female" type="radio" value='F' name="gender" required/> Female
<br/><br/>
Age: <input type="text" id="age" disabled />
<br/>
Body Type:
<select id="Body Type">
<optgroup label="Female" id="FemaleOpt">
<option value="Apple"> Apple </option>
<option value="Pear"> Pear </option>
<option value="Pencil"> Pencil </option>
<option value="Hourglass"> Hourglass </option>
<option value="Round"> Round </option>
</optgroup>
<optgroup label="Male" id="MaleOpt">
<option value="Oval"> Oval </option>
<option value="Triangle"> Triangle </option>
<option value="Rectangle"> Rectangle </option>
<option value="Rhomboid">Rhomboid </option>
<option value="Inverted">Inverted Triangle</option>
</optgroup>
</select>
<br/><br/>
Occupation:
<input id="occu" type="text" size=30 maxlength=30 required />
<br/><br/>
Height(in cm):
<input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
<br/><br/>
<textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
<textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
<br/><br/>
<button id="submit" type="submit">Submit</button>
<button id="findmatches" type="button">Find Matches</button>
</fieldset>
</form>
</div>
</body>
</html>
Do these steps. First you have two window.onload = () (As you are not using addEventListener only one event will be attached).
Steps:
Keep everything intact, just remove the window.onload from both places. Keep all code inside load intact.
Move the entire code block just to the bottom of the html above closing tag. (Doing so, will make window.onload redundant.)
Put console.log() in the click handler and see if it's working (it will)
Let us know.
NOTE: On other hand there are better way to code this, for e.g wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here. First make this work, then we can recommend better approaches.
I am new to Javascript and just getting into it for my web design class. I am working on a project with Javascript inside HTML. I have it all written, but the HTML doesn't seem to call the Javascript function. I've been searching for a solution but can't seem to get anything to work. The code is:
<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
message-box ("Invalid data for principle amount.");
}
}
else {
message-box ("Invalid data for interest rate.");
}
}
</script>
<style>
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
</style>
</head>
<body>
<form>
Enter Principal Ammount : <input type="text" id ="principal" />
</br>
Enter Intrest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>
</form>
</body>
</html>
The browser error is "SyntaxError: expected expression, got '}' " on line 2 but I just can't see what the issue is. Any help is greatly appreciated!
Side note, I am aware there are some weird spelling mistakes. My instructor is from India and not totally fluent in English. She made the HTML file for us to use and we just have to put in the Javascript.
There is no message-box function. Did you mean alert()? Your code currently works, with those changes:
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
alert("Invalid data for principle amount.");
}
}
else {
alert("Invalid data for interest rate.");
}
}
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
<form>
Enter Principal Amount : <input type="text" id ="principal" />
</br>
Enter Interest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Amount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>
</form>
Small Nitpick: Fixed some small typos not related to code. Ammount => Amount. Intrest => Interest.
Here's the scenario: the user inputs two numbers in each box, and chooses from the box Min, Max, and pow. Numbers are unlimited, which are entered by keyboard, it could be any integer, and the result should either be Max/Min/Pow. I already have my option box, and layout ready, but I cannot get my results as it either gives a 'NaN' or nothing at all.
Can someone please help in finding out the error in my code?
<script>
function calc(){
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var oper = document.getElementById('operators').value;
if(oper === 'min')
{
document.getElementById('result').value = Math.min;
}
}
</script>
<select id="operators">
<option value="min">Math.min</option>
<option value="max">Math.max</option>
<option value="pow">Math.pow</option>
</select>
<input type="text" id="num1" value="">
<input type="text" id="num2" value="">
<button onclick="calc();">Evaluate 2 input function</button>
<br><br>
You need to provide arguments to Math.min()
document.getElementById('result').value = Math.min(num1, num2)
See code snippet:
function calc() {
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var oper = document.getElementById('operators').value;
if (oper === 'min')
document.getElementById('result').innerText = Math.min(num1, num2);
else if (oper === 'max')
document.getElementById('result').innerText = Math.max(num1, num2);
else
document.getElementById('result').innerText = Math.pow(num1, num2);
}
<select id="operators">
<option value="min">Math.min</option>
<option value="max">Math.max</option>
<option value="pow">Math.pow</option>
</select>
<input type="text" id="num1" value="">
<input type="text" id="num2" value="">
<button onclick="calc();">Evaluate 2 input function</button>
<br><br>
<h1 id="result"></h1>
I would like to convert the temperature given in Celsius to Fahrenheit degrees or the other way round. I would like the unit to be chosen via radio button form and the converted units calculated with JS function. However, I am doing something wrong, and I am not sure what exactly. Any help would be appreciated. Thanks.
<body>
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p id="myForm>
<form name="units" onsubmit="return convertTemp();" method="post">
<input type="number" id="temp"><br>
Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
And here is my JavaScript function:
function convertTemp() {
alert("Włączyła się");
var x = document.Jednostki.Temperature.value;
if (x == "c"){
alert("Celsjusz");
}
else if (x == "f"){
alert("Fahrenheit");
}
returns false;
}
Here is what I would suggest
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
var num = parseInt(document.getElementById("temp").value, 10);
if (document.getElementById("c").checked) {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else if (document.getElementById("f").checked) {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
Using querySelector:
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
const num = parseInt(document.getElementById("temp").value, 10);
const type = document.querySelector("[name=Temperature]:checked").value;
if (type==="c") {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
First issue I see: returns false; should be return false; (no s).
You should also retrieve the values using document.getElementById():
function convertTemp() {
alert("Włączyła się");
var celsius = document.getElementById('c');
var fahr = document.getElementById('f');
if (c.checked){
alert("Celsjusz");
}
else{
alert("Fahrenheit");
}
return false;
}
document.getElementById("units").onsubmit = convertTemp;
using jquery you can do it raplce this line
var x = document.Jednostki.Temperature.value;
to
var x = $('input[name="Temperature"]:checked').val()
you can see it working here
to get jquery click here
My validation (see below) for the new Europa bank notes did not work. This is the rule:
It needs to first get the length of the note, convert the first two
letters into numbers, and finally add the remaining numbers together.
If the number mod by 9 returns 0, it should return true.
If anyone could help me, that would be great. Thanks.
function formValidationCheck() {
var europaValue = document.form.eurbank.value; //takes value entered
var europaVal1 = europaValue.charCodeAt(0); // get's the first letter
var letter1 = europaVal1 - 65;
var europaVal2 = europaValue.charCodeAt(1);
var letter2 = europaVal2 - 65;
var numbers = euuropaValue.substring(3, 12);
var total = letter1 + letter2 + numbers; // adds total of both letters and numbers
var tcheck = total % 9; // mods total by 9
if (europaValue.length > 12) // checks length
{
document.getElementById('eurbank').style.background = 'pink';
document.getElementById('eurbank').style.border = "solid red 2px";
alert("Bank note number must be less than twleve charaters!");
return false;
}
if (tcheck != 0) //checks the total
{
document.getElementById('eurbank').style.background = 'pink';
document.getElementById('eurbank').style.border = "solid red 2px";
alert("That is an invalid europa bank note.");
return false;
}
}
<form name="form" onsubmit="formValidationCheck();" method="get">
Full name:
<br>
<input type="text" name="fullname">
<br>Phone number:
<br>
<input type="text" name="phonenumber" id="phoneNum" required>
<br>Email:
<br>
<input type="email" name="email" required>
<br>Credit Card Type:
<br>
<select name="credit card type">
<option value="visa">Visa</option>
<option value="master">Mastercard</option>
</select>
<br>Credit Card Number:
<br>
<input type='text' name='creditnum' id='creditnum' required>
<br>Europa Banknote number:
<br>
<input type="text" name='eurbank' id='eurbank' required>
<br>
<input type="submit" value="Purchase Now" />
</form>
</div>
Try parse the letter into integer before doing the numerical operation.
var total = parseInt(letter1) + parseInt(letter2) + numbers;