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.
Related
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>
Fairly new to Javascript here. I have a to do list, and I am in the process of adding a feature to Hide all checked items (which have a class .checked).
The idea i have, is to add a display property to the class(that all checked items receive) but how do I do it? Is there any other way for me to be able to add a display property to all of the checked items?
Here's the code (didn't include the other css as it was unnecesary):
//ADD NEW ELEMENT SECTION
function newElement() {
var inputval = document.getElementById('inputnewlist').value;
var li = document.createElement('li');
var lichild = document.createTextNode(inputval);
li.appendChild(lichild);
if (inputval === '') {
alert('you must put something in the textbox!');
} else {
document.getElementById('mylist').appendChild(li);
}
document.getElementById('inputnewlist').value = "";
//REMOVE BUTTON SECTION
var button = document.createElement('button');
var buttonval = document.createTextNode('x');
button.classList.add("exit");
button.appendChild(buttonval);
li.appendChild(button);
var exit = document.querySelectorAll('.exit');
for (b = 0; b < exit.length; b++) {
exit[b].addEventListener('click', removeButtonParent);
}
}//end of create newelement function
var exit = document.querySelectorAll('.exit');
for (z = 0; z < exit.length; z++) {
exit.addEventListener('click', removeButtonParent);
}
function removeButtonParent() {
event.target.parentElement.remove();
}
//ENTER KEY PRESS-BUTTON PRESS
function enterfunction(event) {
var key = document.getElementById('inputnewlist');
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('addbutton').click();
}}
//CHECK BUTTON SECTION
var list = document.querySelector('ul');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
//HIDE CHECKED LIST ITEMS
function hideCheck() {
if (event.target.checked === true) {
var checkLI = document.querySelectorAll('.checked');
checkLI.style.display = "none";
}
else {
var checkliELSE = document.querySelectorAll('.checked');
checkLI.style.display = "";
}
}
.checked {
background-color: darkgrey;
text-decoration: line-through;
}
<!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">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div id="formcontainer">
<h1 class="title"> To Do List </h1>
<input type="text" name="inputnewlist" id="inputnewlist" placeholder="Add thing to do.." onkeydown="enterfunction(event)">
<button onclick="newElement()" class="addbutton" id="addbutton">Add</button>
</div>
<ul id="mylist">
</ul>
<input type="checkbox" id="hidecheck" onchange="hideCheck()"> <label for="hidecheck"> Hide the checked list items</label>
<script src="scripts.js"></script>
</body>
You can try the following code by adding the style 1 by 1.
function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}
This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 2 years ago.
I am trying to create a working login interface with javascript. I've put down my code but it won't work and it does not show any type of error messages.
Thanks
Taris
function loginFunction() {
var x = document.getElementById("myText");
var y = document.getElementById("myText1");
console.log(x);
console.log(y);
if (x == "Tom" && y == "Halo") {
window.open("www.youtube.de");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
You need to access the .value of the elements x and y - you're dealing with the element, not the value:
if (x.value == "Tom" && y.value == "Halo") { ... }
You forgot to add .value to selected text field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
<script>
function loginFunction () {
var x = document.getElementById("myText").value;
var y = document.getElementById("myText1").value;
console.log(x);
console.log(y);
if(x === "Tom" && y === "Halo") {
console.log("login in");
//window.open("www.youtube.de");
}
else
{
console.log("failed");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
</script>
</body>
</html>
The problem is that you are reading the value of those input elements. You have assigned the input itself to the variable.
var x = document.getElementById("myText").value;
function loginFunction() {
var x = document.getElementById("myText").value;
var y = document.getElementById("myText1").value;
console.log(x);
console.log(y);
if (x === "Tom" && y === "Halo") {
alert('open page')
//window.open("https://youtube.de");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
</body>
</html>
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);
I am trying to make a program that prompts the user to guess a number from 1 to 1000. The program generates a random number and then the user has to guess the number until they get it right. The program alerts the user if their guess is too low or too high. Upon entering the right number, they are congratulated and asked if they want to run it again. I have read my book and even looked online for guidance, but against my best effort all it does is display the text field with the calculate button...no window messages or anything. Please help as I am stumped. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
There is a } missing in line 45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
}
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
Jquery way if you mind
var a = Math.floor((Math.random() * 100) + 1);
$(document).ready(function(){
$('#numberrandom').text(a);
});
$('#calculate').bind('click',function(){
entrynumber=$('#entry').val();
if(entrynumber > a){
alert('Your number is higher than it')
}
else if(entrynumber < a){
alert('Your number is lower than it')
}
else if(entrynumber == a){
alert('nice you won')
location.reload();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
<span>generated number: </span><span id='numberrandom'></span>
</div>
</form>
</body>