"please enter a value" When all input fields are full - javascript

When I put a value into both boxes I still get the error "Please enter a value". If I comment out the second If statement it works fine, just doesn't validate for the fields being left blank. Not sure what's wrong with the if statement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<script src="bmi.js"></script>
<title>BMI Calculator</title>
</head>
<body class="whole">
<h2>BMI Calculator!</h2>
<form>
<section id="whinputs" class="inputs">
<input id="weight" type="text" placeholder="Enter weight in pounds">
<input id="height" type="text" placeholder="Enter height in inches">
</section>
<section class="buttons">
<input type="button" onclick="valid()" value="Calculate BMI">
<input type="reset">
</section>
</form>
<h2 id="resultline"></h2>
</body>
</html>
JS:
var valid = function () {
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
if (isNaN(weight || height)) {
return alert("Value must be a number!");
}
if (weight || height === "") {
return alert("Please enter a value");
}
else {
var result = ((weight / (Math.pow(height, 2))) * 703);
var result = parseFloat(result).toFixed(2)
// return alert("Your BMI is " + result)
return document.getElementById('resultline').innerHTML = ("Your BMI is " + result);
}
}

There are two problems in your code. One being the question you asked, and one you probably haven't noticed yet.
The question you asked
The problem lies in this code:
if (weight || height === "") {
return alert("Please enter a value");
}
The code above translates into:
if [weight is a truthy value] OR [height is an empty string]
then return alert('Please enter a value');
But that's not what you really want. Instead, you should do it this way:
if (weight === '' || height === ''){
return alert('Please enter a value');
}
Which translates to:
if [weight is an empty string] OR [height is an empty string]
then return alert('Please enter a value');
The problem you probably haven't noticed yet
if (isNaN(weight || height)) {
return alert("Value must be a number!");
}
Which translates to:
if weight is a truthy value, then use isNaN(weight), else use isNaN(height)
then return alert('Value must be a number!');
But that's not what you really want. Instead, you should do it this way:
if (isNaN(weight) || isNaN(height)){
return alert('Value must be a number!');
}
Which translates to:
if ( weight is NaN OR height is NaN )
then return alert('Value must be a number!');
Test the code
var valid = function () {
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
/*
if (isNaN(weight || height)) {
return alert("Value must be a number!");
}
*/
if (isNaN(weight) || isNaN(height)){
return alert('Value must be a number!');
}
/*
if (weight || height === "") {
return alert("Please enter a value");
}
*/
if (weight === '' || height === ''){
return alert('Please enter a value');
} else {
var result = ((weight / (Math.pow(height, 2))) * 703);
var result = parseFloat(result).toFixed(2)
// return alert("Your BMI is " + result)
return document.getElementById('resultline').innerHTML = ("Your BMI is " + result);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<script src="bmi.js"></script>
<title>BMI Calculator</title>
</head>
<body class="whole">
<h2>BMI Calculator!</h2>
<form>
<section id="whinputs" class="inputs">
<input id="weight" type="text" placeholder="Enter weight in pounds">
<input id="height" type="text" placeholder="Enter height in inches">
</section>
<section class="buttons">
<input type="button" onclick="valid()" value="Calculate BMI">
<input type="reset">
</section>
</form>
<h2 id="resultline"></h2>
</body>
</html>

The problem is the logic with your if statement. Try this:
if ((weight === "") || (height === "")) {
return alert("Please enter a value");
}

the second if statement is wrong
if (weight || height === "")
will be true if weight has input
you want something likeif (isNaN(weight) || isNaN(height)), if you want to make sure the input is number, you may also want to check whether it is divided by 0

You were checking if weight was defined by leaving is the way it was.
if (isNaN(weight || height)) {
return alert("Value must be a number!");
}
if (weight == "" || height == "") {
return alert("Please enter a value");
}
else {
var result = ((weight / (Math.pow(height, 2))) * 703);
result = parseFloat(result).toFixed(2)
// return alert("Your BMI is " + result)
document.getElementById('resultline').innerHTML = ("Your BMI is " + result);

Related

Trying to add together multiple inputs in the same input field to get total value

tried cutting the code down as much as possible.
Issue: I'm trying to get the total price of new array objects that are being created from inputs by the user, i tried making a new function that grabs the input, but it changes to the new value in the input field whenever a new item is added. Price also wont change when the user deletes an object from the array.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
//Functions for user input for item name and price
function additemmore () {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if(document.getElementById("item-name-more").value.length == 0)
{
alert("Need a name")
return false;
}
if(document.getElementById("item-price-more").value.length == 0)
{
alert("Need a price")
return false;
}
if(document.getElementById("item-price-more").value === 0)
{
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore(){
itemListmore.innerHTML ="";
for(let i = 0; i < itemArrayMore.length; i++){
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
var total = +price;
document.getElementById("total-price").innerHTML = total;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input
type="text"
id="item-name-more"
placeholder="Item name"
/>
<!--for some reason you can add the letter e in the input for price-->
<input
type="number"
id="item-price-more"
placeholder="Write name of item!"
/>
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Make total a global variable. Then you can add to it when you add a new item, and subtract from it when you delete an item.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
var total = 0;
//Functions for user input for item name and price
function additemmore() {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if (document.getElementById("item-name-more").value.length == 0) {
alert("Need a name")
return false;
}
if (document.getElementById("item-price-more").value.length == 0) {
alert("Need a price")
return false;
}
if (document.getElementById("item-price-more").value === 0) {
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore() {
itemListmore.innerHTML = "";
for (let i = 0; i < itemArrayMore.length; i++) {
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
total -= +itemArrayMore[i].price.replace('kr', '');
document.getElementById("total-price").innerHTML = total;
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
total += +price;
document.getElementById("total-price").innerHTML = total;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input type="text" id="item-name-more" placeholder="Item name" />
<!--for some reason you can add the letter e in the input for price-->
<input type="number" id="item-price-more" placeholder="Write name of item!" />
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>

Adding JavaScript calculation function to HTML form

I am trying to link a basic calculation in an external JavaScript
The form is pretty simple and the function just checks to make sure the step number is even. I have reviewed the code many times, but when I enter the numbers and hit submit nothing happens. Any suggestions? Its seems like I just don't have the function and input elements linked correctly.
here is the code:
function evenNumbers() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="number" id="startNumber"/><br/>
<label>End: </label>
<input type="number" id="endNumber"/><br/>
<label>Step by:</label>
<input type="number" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
Try this:
In .js file
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
I have removed your actual code for now, because it has some issues whereby you can end up in an infinite loop (I definitely did and it crashed Chrome 😊).
Your issue was in your HTML
Before
<button onclick("evenNumbers();")>Submit</button>
After
<button onclick="evenNumbers();">Submit</button>
function evenNumbers() {
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
alert(startNumber + ',' + endNumber + ',' + stepNumber);
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
function evenNumbers() {
//var evenNumberBtn = document.querySelector("button");
//evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers()">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
The first two lines inside evenNumber function need to be outside the function, Otherwise your code never reaches inside that block.
$( document ).ready(function() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
function evenNumbers() {
/*
your code here
*/
}
});
Also the logic inside the evenNumbers seems wrong. You might need to change that too.

Why is `pieceOfText` undefined?

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?
You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

Part of my coding in javascript not working

For some reason, the validation for duration is having problem such as when I try to type 30000000 for the duration and submit,it just never do its validation but the rest of the validation works for some reason.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var y =document.forms.myForm.percentage.value;
if(y>=0 && y<=100)
{
return true;
}
else
{
alert("Percentage output must be between 0 and 100");
return false;
}
var k =document.forms.myForm.duration.value;
if(k>=0 && k<=30000)
{
return true;
}
else{
alert("Error");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return validateForm();">
Enter access token: <input type="text" name="token">
Enter device id: <input type="text" name="id">
Enter output percentage: <input type="text" name="percentage">
Enter duration(in milliseconds) of output: <input type="text" name="duration">
<input type="submit" value="Submit">
</form>
</body>
</html>
Cause:
function validateForm() {
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var y =document.forms.myForm.percentage.value;
if(y>=0 && y<=100)
{
return true; //<---- You leave your code here!!
}
else
{
alert("Percentage output must be between 0 and 100");
return false;
}
var k =document.forms.myForm.duration.value;
if(k>=0 && k<=30000)
{
return true;
}
else{
alert("Error");
return false;
}
}
Look at the arrow in the code I entered.
In the percentage check, you always return! The duration check is never reached. You should remove all your if/else cases which ends in return true, only check on error and return false in that case. Otherwise return true as the last line of your method.
If you want to alert on more than one error, you can do something like the following, though you'd have to format the alert message text so that each error is on its own line:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var errors = [];
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var percentage = document.forms.myForm.percentage.value;
if(!(percentage >= 0 && percentage <= 100)) {
errors.push("Percentage output must be between 0 and 100");
}
var duration = document.forms.myForm.duration.value;
if(!(duration >= 0 && duration <= 30000)) {
errors.push("Duration output must be between 0 and 30,000");
}
if (errors.length > 0) {
alert(errors);
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return validateForm();">
<p>Enter access token: <input type="text" name="token"/></p>
<p>Enter device id: <input type="text" name="id"/></p>
<p>Enter output percentage: <input type="text" name="percentage"/></p>
<p>Enter duration(in milliseconds) of output: <input type="text" name="duration"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>

No output from javascript function

I am really new to programming and this has had me stumped for days. I'm trying to do a really simple postage calculator. The function on its own works fine but when I tried to link it to user input im getting no output. Any help with this would be much appreciated.
Here's what I have been trying..
<!DOCTYPE html>
<html>
<head>
<title>postage calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<div>Postage Calculator</div>
<input id="amount" type="text" name="purchasePrice" placeholder="0" />
<input id="submit" type="submit" value="submit" />
<script type="text/javascript">
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
function aberdeen(){
var weight = parseFloat(amount.value) || 0;
if(weight>0 && weight<500){
return total = 3.50;
}
else if(weight<501 && weight<750){
return total = 4.30;
}
else if(weight<751 && weight<1000){
return total = 5.10;
}
else if(weight<1001 && weight<1250){
return total = 5.90;
}
else if(weight<1251 && weight<1500){
return total = 6.70;
}
else if(weight<1501 && weight<1750){
return total = 7.50;
}
else if(weight<1751 && weight<2000){
return total = 8.30;
}
else{
return 0;
}
}
submit.addEventListener("click", aberdeen, false);
</script>
</body>
</html>
You need to have element that will have the output of the calulation like:
<div id="output"></div>
var output = document.getElementById('output');
submit.addEventListener("click", function() {
output.innerHTML = aberdeen();
}, false);
You need to bind the eventListeners after the elements you are listening to are loaded.
The output has to be displayed somewhere. It can be either displayed in a textbox, a HTML-element or a simply alert() -box. I have used a text box in my example using element.
Also I created a working version of your code:
<!DOCTYPE html>
<html>
<head>
<title>postage calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<div>Postage Calculator</div>
<input id="amount" type="text" name="purchasePrice" placeholder="0" />
<input id="submit" type="submit" value="submit" />
<input id="userPays" type="text" name="userPays" />
<script type="text/javascript">
function aberdeen(amount){
var weight = parseFloat(amount) || 0;
if(weight>0 && weight<500){
return 3.50;
}
else if(weight<501 && weight<750){
return 4.30;
}
else if(weight<751 && weight<1000){
return 5.10;
}
else if(weight<1001 && weight<1250){
return 5.90;
}
else if(weight<1251 && weight<1500){
return total = 6.70;
}
else if(weight<1501 && weight<1750){
return 7.50;
}
else if(weight<1751 && weight<2000){
return 8.30;
}
else{
return 0;
}
}
window.onload = function() {
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
var userPays = document.getElementById("userPays");
function count(){
userPays.value = aberdeen(amount.value);
}
submit.addEventListener("click", count, false);
}
</script>
</body>
</html>
See demo at: http://codepen.io/anon/pen/zxaaQe
Make sure your logic to calculate values is correct as some commenters have suggested.

Categories

Resources