JavaScript GPA form validator - javascript

I am trying to create a form which will ask a sure to input name, GPA and phone number. I need help to validate the GPA to be a number between 0 and 4 inclusive, including at most two decimal values after the grade.
I cannot figure where to start!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function enter()
{
var grade = document.getElementById("gpa").value;
if (grade >= 0 && grade <= 4)
{
alert("success");
}
}
</script>
</head>
<body>
<form id= "survey" name="survey">
Name:
<input type="text" name="fullname"/><br>
GPA:
<input type="text" id="gpa" name="gpa" maxlength="4"/><br><br>
<input type="submit" onclick="enter()"/>
</form>
</body>
</html>

Try something like this, its written with just javascript and html.
window.verify = function() {
var gpa = document.getElementById("gpa").value;
var ver = parseFloat(gpa);
alert(ver >= 0 && ver <= 4);
}
<input type="text" id="gpa" />
<br>
<br>
<button type="submit" onclick="verify()">Check GPA

Related

When I click the Calculate button, it does not display the calculations in textbox for sales tax and total

When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

I am trying to convert Fahrenheit to Celsius but it's not working what am i doing wrong? - Javascript (needs to have a form and a clear button)

<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
cel = fah * 0.5555 - 32;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Edit1: Moved the inner.HTML into the Function
So the reset button is the only thing that works. Is it possible to calculate the math this way?
You asked a question on how to create a pizza form a while ago and you deleted it soon as it was down voted a few times.
The point to note here is, it is okay if a few people dislike your question. You've joined StackExchange not to gain points but to learn a few things. Your question could be helpful to a lot of others out there in this world. So here it is the answer to your pizza question
<html>
<body>
<p>A pizza is 13 dollars with no toppings.</p>
<form action="form_action.asp">
<input type="checkbox" name="pizza" value="Pepperoni" id="pep">Pepperoni + 5$<br>
<input type="checkbox" name="pizza" value="Cheese" id="che">Cheese + 4$<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<input type="button" onclick="cost()" value="Get cost">
<br><br>
<input type="text" id="order" size="50">
</form>
<script>
function myFunction() {
var pizza = document.forms[0];
var txt = "";
var i;
for (i = 0; i < pizza.length; i++) {
if (pizza[i].checked) {
txt = txt + pizza[i].value + " ";
}
}
document.getElementById("order").value = "You ordered a pizza with: " + txt;
}
function cost() {
var pep = 5;
var che = 4;
var pizza = 13;
var total = 0;
if (document.getElementById("pep").checked === true) {
total += pep;
}
if (document.getElementById("che").checked === true) {
total += che;
}
document.getElementById("order").value = "The cost is : " + total;
}
</script>
</body>
</html>
Thanks. I hope this helps you.
Adeno Fixed it by declaring what fah was. you can also see your errors with f12.
https://stackoverflow.com/users/965051/adeneo
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate(form) {
var cel = (document.getElementById("fah").value -32) * 5 / 9;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius!
<br>
<input type="number" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
You never get the value from the input type = "number"
Try this
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function calculate()
{
var fah = document.getElementById('fah').value;
var cel = parseFloat(fah * 0.5555 - 32);
document.getElementById("finish").innerHTML = cel;
}
</script>
</head>
<body>
<form>
Turn Fahrenheit to Celsius! <br>
<input type="text" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate()">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Couple things: You need to set the innerhtml from within the function because the variable is in the function. Or you could have declared the variable outside the function first like var fah = "" then the function. But since you declared it in the function only the function can see it. So i moved the innerhtml set into the function.
Also, javascript likes to use id's not name = "fah" You can call an element by name but id is easier.
i rounded it to integer. you would get 9 decimals your way.
Lastly, innerhtml set clears all the html so you would lose the °C the way you had it.
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
var fah = this.fah.value;
cel = Math.round((fah-32) / 1.8);
document.getElementById("finish").innerHTML = cel+"°C";
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah" id = "fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish"></p>
</body>
</html>

Simple calculation from user input

This is my first time dealing with HTML and javascript, so pardon this simple question. I am trying to calculate the cost total cost of the fruits that the user wants to purchase. It was working fine earlier on but somehow it stopped working. May I know what is wrong here?
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
</head>
<body>
<form name="orderForm" action="orderProcess.php" onsubmit="return validateForm()" method="post">
<h1>My header</h1>
<label>User Name: </label>
<input type="text" name="username"> <br>
<label>Number of Apples ($0.69 / ea): </label>
<input type="text" name="AppleQty" id="AppleQty" oninput="calculateCost()"> <br>
<label>Number of Oranges ($0.59 / ea): </label>
<input type="text" name="OrangeQty" id="OrangeQty" oninput="calculateCost()"> <br>
<label>Number of Bananas ($0.39 / ea): </label>
<input type="text" name="BananaQty" id="BananaQty" oninput="calculateCost()"> <br>
<label>Total Cost: $</label>
<input type="text" name="totalCost" id="totalCost" readonly> <br>
</body>
<script type="text/javascript">
function calculateCost()
{
var appleQty = document.getElementById("AppleQty");
var orangeQty = document.getElementById("OrangeQty");
var bananaQty = document.getElementById("BananaQty");
if(isNaN(appleQty.value))
{
alert('Only Numeric Values Allowed');
appleQty.value = '';
appleQty.focus();
return false;
}
else if(isNaN(bananaQty.value))
{
alert('Only Numeric Values Allowed');
bananaQty.value = '';
bananaQty.focus();
return false;
}
else if(isNaN(orangeQty.value))
{
alert('Only Numeric Values Allowed');
orangeQty.value = '';
orangeQty.focus();
return false;
}
else
{
document.getElementById("totalCost").value = (appleQty.value * 0.69 + orangeQty.value * 0.59 + bananaQty.value * 0.39).toFixed(2);
}
}
</script>

Javascript Shipping Calculator Not Grabbing Input

I am getting the headache of a lifetime. I'm not too great with Javascript so I have no idea what's going on. I'm supposed to be coding a text box that when a price is entered and submitted it will calculate the shipping and tell you the total. Everything is working except for the fact that the typed value isn't being set. So the price seems to be permanently set at NaN no matter what is inputted. What am I doing wrong? D:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price + shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5;
} else {
return price * 10 / 100
}
}
/* ]]> */
</script>
</body>
</html>
Here is a sample which may help you
<input id="amount" type="text" name="purchasePrice" placeholder="0.00" />
<input id="submit" type="submit" value="submit" />
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
function calculateShipping() {
var price = parseFloat(amount.value) || 0;
if (price <= 25) {
alert("Your total is $" + 1.5);
} else {
alert("Your total is $" + (price * 10 / 100));
}
}
submit.addEventListener("click", calculateShipping, false);
on jsfiddle
JavaScript code runs before it knows price... so anything *,+ NaN is... NaN.
You should call calculation of total while submit is clicked, f.ex. this way:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='calculateTotal()'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
function calculateTotal() {
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
window.alert("Your total is $" + total + ".");
}
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100 }
}
/* ]]> */
</script>
</body>
</html>
You need to attach an event handler that fires when the user enters a value.
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<label for="purchasePrice">Price:</label>
<input type="text" name="purchasePrice" id="purchasePrice" placeholder="0.00" />
<br>
<label for="shipping">Shipping:</label>
<input type="text" name="shipping" id="shipping" disabled>
<!-- <input type="submit" value="submit" /> -->
</form>
<script>
var price;
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100;
}
}
var pp = document.getElementById("purchasePrice");
pp.onkeyup = function(e){
price = calculateShipping(this.value);
document.getElementById("shipping").value = price;
};
</script>
This kind of thing really is easier with a library like jQuery. It also handles the differences between browser implementations for attaching event handlers.

Categories