I'd like to add a function to this code that will display the difference between the values calculated by the other two currently implemented functions but I'm unsure how to implement it.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
</head>
<body>
<div>
<header>
</header>
<main>
<p>Your current daily goal is:<span id="UserGoal"></span></p>
<br>
<p>Your current calories eaten for the day:<span id="EatenCalories">0</span></p>
<br>
<p>Remaining calories for today:<span id="RemainingCalories"></span></p>
<label for="Goal">Please enter your daily Goal</label>
<input type="number" id="Goal" name="Goal">
<input type="submit" onclick="updateGoal();"/>
<br>
<input type="number" id="addCalories" name"addCalories">
<input type="button" value="Update Calories" onclick="addCalories();"/>
</main>
<script>
function updateGoal(){
this.UserGoal = document.getElementById("Goal").value;
document.getElementById("UserGoal").innerHTML = this.UserGoal;
}
function addCalories(){
if (this.EatenCalories = ''){ //made 1 = sign, made check ''
this.EatenCalories = document.getElementById("addCalories").value;
document.getElementById("EatenCalories").innerHTML = this.EatenCalories;
}
else{
this.EatenCalories = document.getElementById("EatenCalories").innerText;
parseFloat(EatenCalories);
this.Calories=document.getElementById("addCalories").value;
this.Result=parseFloat(this.Calories)+parseFloat(this.EatenCalories);
document.getElementById("EatenCalories").innerHTML = this.Result;
}
}
</script>
</div>
</body>
</html>
Both the functions store their results in HTML elements by updating their innerHTML
Your new function can use these values to calculate the difference and put the result into another HTML element’s innerHTML to display it.
For example,
<div id=“difference”></div>
function calcDifference() {
document.getElementById("difference").innerHTML = document.getElementById("EatenCalories").innerHTML - document.getElementById("UserGoal").innerHTML;
}
Related
I want the programme to get the biggest number that the user has enter in one of the input boxes and display the bigger number to the user.I would also like some improvements to my code. I would it also be possible to do it with one input box instead of two
<!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>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button >Submit</button>
<div id="store"></div>
<script>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
function max(){
const element = document.createElement('div');
const num1 = box1.value;
const num2 = box2.value;
if (num1<num2 ){
element.innerHTML= num2;
store.appendChild(element);
}
if (num2<num1){
element.innerHTML= num1;
store.appendChild(element);
}
}
</script>
</body>
</html>
First of all, ECMAScript comes with a Math.max() function, so there is no need to re-implement that comparison logic.
Also, your max function doesn’t run automatically. You need to register it as an event listener on the “Submit” button using addEventListener and the click event in order to have it invoked upon clicking the button.
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
const button = document.getElementById('submit');
// upon clicking on the button …
button.addEventListener('click', () => {
max(); // … run `max()``
});
function max() {
const element = document.createElement('div');
element.innerText = Math.max(box1.value, box2.value);
store.appendChild(element);
}
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button id="submit">Submit</button>
<div id="store"></div>
Of course, there is not yet a validation that checks if the given values are actually numbers.
I don’t understand your request about doing it with only “one input box”, though, as determining the larger number (out of many) implies having more than one input, so please specify. Do you mean “multiple values in one input box” like comma-separated?
Yes, you can do it all in one input please see the code below
<!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>Get largest number</title>
</head>
<body>
<input type="text" class="myinput" placeholder="Enter your numbers seperated by commas only">
<button class="submit">Get Max</button>
<h1 class="output"></h1>
<script>
const inputElement = document.querySelector('.myinput');
const submitButton = document.querySelector('.submit');
const outputElement = document.querySelector('.output')
submitButton.onclick = function(){
let inputValue = inputElement.value;
if(inputValue !== ''){
try{
let numbers = inputValue.split(',').map(e=>eval(e));
const maxNumber = Math.max(...numbers);
outputElement.innerHTML = 'Largest Number: ' + maxNumber;
}catch(e){
outputElement.innerHTML = 'Incorrect input format!';
}
}
}
</script>
</body>
</html>
The code takes comma separated input from the user and converts it into an array using the split function. Each value separated by the comma will be an array item. I also mapped it to convert the numbers that were in string form to integer form using the eval function. then I used the try catch block to detect any input format errors that may occur that the program will not be able to process and push an error to the user that they have used the incorrect format.
I hope that helps alot!
So I'm making my first electron app after a 7 hour js crash course and 1 semester of AP Computer Science Principles so I'm pretty new, so bare with me. Im making a shop script app in electron and I have a preliminary basic UI setup in electron with a main.js file which handles the opening of the app and UI stuff. Now I wanted to make the first content script part of the app that actually does stuff (save.js). Essentially the finished UI will have 4 user input fields and I need to take those inputs from the html input/form and save them as variables, then display them on the screen. My variables will be (link, price range, Brand, Model). From the course I took I tried to use document.getElementById in a variable and then using .textContent in an onclick function, so that when the html button is pressed it displays the user input on a section of the page. It didn't work, so I tried this approach and it still doesn't return the input into the UI. Any help is appreciated.
Here is the save.js:
let displayLink = document.getElementById('loggedLink')
function getVal() {
const val = document.querySelector('input').value;
console.log(val);
displayLink.textContent = (val);
}
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Link</title>
</head>
<body>
<script src="save.js"></script>
<form>
<div>
<label>Enter Item</label>
<input type="text" id="itemEl" autofocus>
</div>
<button onclick="getVal()" type="submit">Add Item</button>
<span id="loggedLink">Consoloe: </span>
</form>
</body>
</html>
change in JS
function getVal() {
let displayLink = document.getElementById('loggedLink')
const val = document.querySelector('input').value;
console.log(val);
displayLink.textContent = 'Consoloe: ' + (val);
}
change in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Link</title>
</head>
<body>
<script src="save.js"></script>
<form>
<div>
<label>Enter Item</label>
<input type="text" id="itemEl" autofocus>
</div>
<button onclick="getVal()" type="button">Add Item</button>
<span id="loggedLink">Consoloe: </span>
</form>
</body>
</html>
I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>
I'm trying to grab an input value with javascript and render it into a div element. What do I do to make it work?
I'm using querySeclector to grab the input value. When I hardcode it like this:
document.getElementById("result").innerHTML = "Hello World";
It works but doesn't when I replace "Hello World" with the variable that stores the input value and when I do a console.log, I get nothing back even though there are no errors.
HTML
<body>
<div id="container">
<div id="values">
<input id="firstinput" type="text" placeholder="Enter 2 positive figures">
<button id="submit">Submit</button>
</div>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
JAVASCRIPT
let submitButton = document.querySelector("#submit"),
showResult = document.getElementById("result").innerHTML,
weightsForLeftAndRightSides = document.querySelector("#firstinput").value;
submitButton.addEventListener("click", weightBalancer);
function weightBalancer() {
showResult = weightsForLeftAndRightSides;
console.log(weightsForLeftAndRightSides);
}
you need get input value inside weightBalancer when sumbit button clicked
function weightBalancer() {
var weightsForLeftAndRightSides = document.querySelector("#firstinput").value;
document.getElementById("result").innerHTML = weightsForLeftAndRightSides;
}
if i understood your question, you can write this code to put the user input in div tag:
<!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">
<title> Test</title>
<script >
/*to put the user input in div tag*/
function myFunction(){
const userInput=document.querySelector("#firstinput");
const output=document.querySelector("#result");
output.innerHTML=userInput.value;//this parte overwrite the first input
}
</script>
</head>
<body>
<body>
<div id="container">
<div id="values">
<input id="firstinput" type="text" placeholder="Enter 2 positive figures">
<button id="submit" onclick="myFunction()">Submit</button>
</div>
<div id="result"></div>
</div>
</body>
</html>
Hope this helps
When I'm Trying to Store Array using local Storage it's giving me not the desired Result Why ?..
Here is the code that i've written
<html>
<head>
<script type="text/javascript">
var Array=[];
function addToList(){
var Name=document.getElementById('Name');
Array.push(Name.value);
if(window.localStorage){
localStorage.setItem("name",Name);
}
}
</script>
<title>Local Storage Demo</title>
</head>
<body>
<h1>Local Strorage</h1>
<div>
<input type="text" id="Name" name="Name"> </input>
<button onclick="addToList()">Add</button>
</div>
</body>
</html>
This has already so many answers on the Stack Overflow. Learn to Search things Properly anyway
You need to use JSON.stringify. That turns an object in to a JSON text and stores that JSON text in a string.
And also while retrieving value you need to parse it using JSON.parse which turns json text back into an object.
Here is one sample code that will help you
<html>
<head>
<script type="text/javascript">
var carArray=[];
function addToListCarArray(){
var newCarName=document.getElementById('carName');
carArray.push(newCarName.value);
if(window.localStorage){
localStorage.setItem("carNameKey",JSON.stringify(carArray));
}
}
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
for (i=0;i<carNames.length;i++){
alert(carNames[i]);
}
}
}
</script>
<title>Local Storage Demo</title>
</head>
<body>
<h1>Demo of Local Strorage</h1>
<div>
<input type="text" id="carName" name="carName"> </input>
<button onclick="addToListCarArray()">Add Car</button>
<button onclick="readCarNames()">Display</button>
<p id="displayCarNames"></p>
</div>
</body>