This is a BMI calculator. I expect to check the data validation first. text fields cannot be empty. And then calculate the BMI and display into another text box.. Validation part is working properly, but the calculating function is not. Please help me to find the error.
function validate() {
if (document.myForm.weight.value == "") {
alert("Please provide your weight!");
document.myForm.weight.focus();
return false;
}
if (document.myForm.height.value == "") {
alert("Please provide your heught!");
document.myForm.height.focus();
return false;
}
calBMI();
}
function calBMI() {
var weight = getElementById("weight").value;
var height = getElementById("height").value;
var bmi = weight / (height * height);
document.getElementById("bmi").innerHTML = bmi;
}
<body>
<form name="myForm">
<label>weight</label>
<input type="text" name="weight" id="weight">
<label>height</label>
<input type="text" name="height" id="height">
<input type="text" readonly="readonly" id="bmi">
<input type="submit" value="Submit" onclick="validate() calBMI()">
</form>
</body>
function validate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
if (height == "" || height == 0) {
document.getElementById("result").innerHTML = "Please enter a valid height";
return;
}
if (weight == "" || weight == 0) {
document.getElementById("result").innerHTML = "Please enter a valid weight";
return;
}
calBMI();
}
function calBMI() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var bmi = weight / (height * height);
document.getElementById("result").innerHTML = `BMI: ${bmi}`;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>Weight</div>
<input type="number" id="weight">
<div>Height</div>
<input type="number" id="height">
<input type="submit" value="Submit" onclick="validate()">
<div id="result"></div>
</body>
</html>
Add proper functions to calculate bmi. No need to call calculatebmi on submit.
var form = document.getElementsByName('myForm')[0];
form.addEventListener('submit', validate);
function validate(e) {
e.preventDefault();
if (document.myForm.weight.value == "") {
alert("Please provide your weight!");
document.myForm.weight.focus();
return false;
}
if (document.myForm.height.value == "") {
alert("Please provide your heught!");
document.myForm.height.focus();
return false;
}
var weight = document.myForm.weight.value;
var height = document.myForm.height.value;
calBMI(weight, height);
return true;
}
function calBMI(w, h) {
var bmi = Math.ceil((w / Math.pow(h, 2)) * 703);
document.getElementById("bmi").setAttribute('value', bmi);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form name="myForm">
<label>weight</label>
<input type="text" name="weight" id="weight">
<label>height</label>
<input type="text" name="height" id="height">
<input type="text" readonly="readonly" id="bmi">
<input type="submit" value="Submit" onclick="validate();">
</form>
</body>
</html>
Related
I currently have this code:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
}
mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
Currently this code will turn any card input details to red regardless if they are valid (I was previously having problems as detailed here Changing Input background colour on invalid. However I know that 4111-1111-1111-1111 for example is a valid card number yet the input field will turn red and not allow me to submit the form. My question is how would I go about changing my current code to allow 4111-1111-1111-1111 as well as other valid card numbers to be accepted?
You need to make sure you only set setCustomValidity if it is really invalid, and if not set it back to blank string
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;// make sure you return here!!
}
mythis.setCustomValidity("");
}
Working example:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;
}
mythis.setCustomValidity("");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I changed your condition in checkLuhn function to make sure that when it is true it shows green, else it is red:
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
This is what you mostly forgot: mythis.setCustomValidity(''); to make sure it is valid
DEMO
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
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>
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
I have this html code with javascript. My average value displays correctly but my find minimum is not displaying anything. Its supposed to show when the user clicks on the find min button on the box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateGrade = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) ) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("average").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if ( (exam1<exam2) && (exam1<exam3)){
$("mini").value=exam1;}
else if ((exam2<exam1) && (exam2<exam3)){
$("mini").value=exam2;}
else {
$("mini").value=exam3;
}
}
window.onload = function () {
$("calculate").onclick = calculateGrade;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Average</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="average"disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var average = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("result").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
} else {
$("result").value = Math.min(exam1,exam2,exam3);
}
}
window.onload = function () {
$("average").onclick = average;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="result" disabled ><br>
<label> </label>
<input type="button" id="average" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
The issue is with the min function. Instead of setting the value of textbox (probably, missing in your code example) you are setting the value of button "mini" (which is incorrect).
Update:
You need to be including one more textbox <input type="text" id="txtMin" disabled ><br>
and update your min function to set the value of it, as follows:
$("txtMin").value=exam1;
...
$("txtMin").value=exam2;
...
$("txtMin").value=exam3;
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.