I think this is a simple fix but I cannot for the life of me seem to think about why this isn't working.
I'm a complete novice at JavaScript and HTML as you can probably tell by the code below but I just want it to be functional so I can learn by it.
The goal is to take two of the input values (what the user puts into those boxes specifically) and then divide and multiply that value with a specific integer that doesn't change and output the result into a paragraph.
function calculateValues(){
let pretext = document.getElementById("preresults");
let userinput = document.getElementById("results");
let userdistanceboxinput = document.getElementById("distancebox").innerText;
let userfuelboxinput = document.getElementById("fuelinputbox").innerText;
let oneimperialgallontolitre = 4.546;
let oneimperialgallontous = 1.201;
userinput.style.visibility = 'visible';
pretext.style.visibility = 'visible';
userinput = (userdistanceboxinput / userfuelboxinput) * 4.544;
The function is tied to an onclick event on a submit button as follows:
<button type="submit" id="submitbutton" onclick="calculateValues()" value="Submit">Submit</button>
Any help with this would be appreciated.
To get a value in Javascript, you can do this:
<input type="number" id="input1">
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
const value1 = input1.target.value; // retrieve the value of this element
If you want to set a HtmlInputElement value you can do (same html):
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
input.target.value = value1 * 21545 // set value of HtmlInputElement
Related
In the script below, I want to be able to display on the main html page lists of paragraphs saved in the localstorage. In the html I defined an are with the id "content". I want to display the texte stored in the localstorage in this area.
In the script below the function "displaylocalstorage" does not allow me to display the values that have been saved in the localstorage with the function "storedparagraphs". Can you please give me some guidelines to correct the "displaylocalstorage" function? Is my while loop correct ? Is the way I call the fucntion "display locastorage" is correct ?
Here is the html and js script below:
Javascript:
const mybutton = document.getElementById ("addbutton");
const mytext = document.getElementById("mytext");
const content = document.getElementById("content");
function displaylocalstorage() {
let n = 0;
while (localStorage.getItem("content" + n)) {
n++;
}
while (n){
const paragraph = document.createElement("p");
paragraph.innerText = localStorage.getItem("content");
content.appendChild(paragraph);
n++
}
}
}
displaylocalstorage()
displaylocalstorage is not being called.
add this to your js
const buttonshow = document.getElementById("buttonshow");
buttonshow.addEventListener("click", displaylocalstorage);
and to your html:
<input
type="button"
value="show"
id="buttonshow"
class="buttonshowall"
/>
and console log items in the displaylocalstorage
Thank would be a good start. Other than this in that paragraph remove length from n as n is a number. If you keep it as length it will error.
if(n>0){
let lastposition = n -1;
localStorage.removeItem("content", lastposition)
}
Another big one is change const n to let as you try to update n and const won't allow you to do that.
I want to get the value of an input type number and put it into a global variable. But in the console I get undefined. I need to use the value in other functions. How can I do that?
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
}
console.log(Inputvalue)
<input type="number" id="bet" value="" name="bet">
The checkBet() function will only be called after you change the value in the input. However, console.log() gets called right away, just as the JS parser reads the file. Since you've not assigned any value to the variable, you will get undefined.
You should either initialize the variable with a value (like 0), or move the console.log() inside the checkBet() function.
Option 1:
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
console.log(Inputvalue)
}
Option 2:
const bet = document.querySelector('#bet');
let Inputvalue = 0;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
}
console.log(Inputvalue)
Try this.
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet);
function checkBet(e) {
Inputvalue = e.target.value;
console.log(Inputvalue)
}
<input type="number" id="bet" name="bet"/>
Hope this helps
I am trying to get the value from an input field and display it using a div tag, but it's not displaying anything. Where am I wrong?
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers').innerHTML = num;
<input type="text" id="inputNum">
<div id="numbers">
</div>
Here is the code,
HTML
<input type="text" id="inputNum">
<div id = "numbers">
</div>
Javascript
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.onkeyup= function(e){
numbersList.innerHTML = e.target.value;
}
keyup will detect every key that is being typed and it will display to the div
Use a onkeyup event. This will give you ever character from text box. After getting the value you can easily set it using innerHTML. Consider the following snippet:
<script>
function setValue(){
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
}
</script>
<input type = "text" id ="inputNum" onkeyup="setValue()">
<div id = "numbers">
In var numbersList = document.getElementById('numbers').innerHTML = num; just omit var numbersList =. Code document.getElementById('numbers').innerHTML = num; will set innerHTML of Element with Id = "numbers" and will not return anything.
Your code will be:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
or just
document.getElementById('numbers').innerHTML = document.getElementById("inputNum").value;
You have a few problems, and your needs aren't totally clear, but hopefully this will help. Here are the things I fixed:
This line
var numbersList = document.getElementById('numbers').innerHTML = num;
contains an error because it has two equals signs. I replaced it with two lines, first identifying the element and saving it to the variable numbersList, then setting the innerHTML property of numbersList to the num discovered above.
Secondly, the javascript you've written will presumably run once, when the page is loaded. At that time the input contains no text, so there's nothing to copy to the div. Depending on what you're trying to do, there are a few ways to handle this, but as one example, I've put the code you wrote (with the above fix) into a function, then added a button and assigned the function to run when the button is clicked.
Please let me know if you have any questions.
function copyVal() {
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers')
numbersList.innerHTML = num;
}
document.getElementById('copy').onclick = copyVal;
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
<button id="copy">copy text</button>
So a few things is happening below.
First, we ensure that the whole page is loaded. Why? If your script is loaded at the beginning, it may have troubles accessing the DOMs (input, textarea, div, etc). Of course, if you load the Javascript at the botton of your page, you can skip such issue.
However, I decided to implement the (function() {...}); self-execute function. This will ensure your Javascript runs after the page its loaded.
Then, I added an event listener to the DOM object of inputNum. This listener will keep an eye to keyup events of your keyword. Each time a key goes up, after being pressed, it will run the code inside the function.
// This function will execute when the whole page is loaded
// This means that all the DOMs (such as your input and div) will be available
(function() {
var inputNum = document.getElementById("inputNum");
inputNum.addEventListener("keyup", function(){
var num = inputNum.value;
document.getElementById('numbers').innerHTML = num;
});
})();
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
Note: I could have use the attribute keyup='' in the input field; however, I decided to give you an answer that provides 100% control. In this way, you can decide which type of event is more appropriate to the project you are working with.
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.addEventListener('change', function(){
numbersList.textContent = this.value;
})
Try this:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
How would one go about stacking values to each other? So if you were to click on a button, it would add the numbers to each other and keep stacking on. I'm trying to add the values to a P tag's innerHTML that calculates the total but I just figured out how to display its true value without the addition of additional values.
const input = document.querySelector('input')
const button = document.querySelector('button')
const p = document.querySelector('p')
function addCal() {
const inputVal = input.value
p.innerHTML = inputVal
}
button.addEventListener('click', addCal)
<input type="text"/>
<button>Add Calories</button>
<p>0</p>
You just need to keep track of the last value somewhere and add that to the newest number.
Keep in mind that all values gotten from HTML are strings, so they must be converted (implicitly or explicitly) to numbers before math can be done. Also, .innerHTML is for when you are getting/ setting strings that contain HTML. When you aren't doing that, use .textContent.
Also note that you should always verify user input is what you think it is before you operate on it. What if the user doesn't enter anything, but clicks the button anyway? What if they enter non-numeric data?
const input = document.querySelector('input');
const button = document.querySelector('button');
const p = document.querySelector('p');
var total = null; // The running total will be kept here
function addCal() {
const inputVal = input.value;
// .parseInt() and .parseFloat() are two ways of
// explicitly converting strings that contain number
// characters to numbers. With .parseInt() the secon
// argument is the radix, which specifies what numeral
// system to use (base 10 here).
total = total + parseInt(inputVal, 10);
p.textContent = total;
}
button.addEventListener('click', addCal)
<input type="text"/>
<button>Add Calories</button>
<p>0</p>
One of the easiest ways is to use reduce to sum all the input values.
1) Pick up all the inputs with querySelectorAll.
2) Then iterate over the input elements with reduce adding each input's value to the total sum. We use +input.value to coerce the string type of the value to a number.
const inputs = document.querySelectorAll('input');
const button = document.querySelector('button');
const para = document.querySelector('p');
function addCal() {
para.textContent = [...inputs].reduce((sum, input) => {
return sum += +input.value;
}, 0);
}
button.addEventListener('click', addCal, false);
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<button>Add Calories</button>
<p>0</p>
Just do convert p tag value to int and then added up. like
function addCal() {
const inputVal = input.value
p.innerHTML = ( parseInt(p.innerHTML) + parseInt(inputVal) )
}
I have a silly fiddle that I am stuck with, I am trying to take the beginning number and double it every time the x2 button is hit. Instead of this behavior I am getting [object HTML ParagraphElement] returned instead. I am re-learning JavaScript so I am trying to work with just JavaScript, no frameworks etc...
var inputVal = document.getElementById("input").value;
var inputEl = document.getElementById("input");
var doubleButton = function () {
var sum = 0;
Number(input);
sum = input + input;
inputEl.value = input;
inputEl.innerText = input;
}
var boom = function () {
alert("BOOM!!!!! Dont you know you should never press the big red button")
}
document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
document.getElementById("btnRed").addEventListener("click", boom, false);
<p>Enter a number and click the x2 button to have it doubled</p>
<p id="input">5</p>
<br>
<button id="btnAdd">x2</button>
<br>
<button class="redBtn" id="btnRed">BIG RED BUTTON</button>
here is the link to my actual fiddle http://jsfiddle.net/jpb4815/uynfc1ky/16/
Why is my code returning object and not the number, I thought that I had taken care of that with the number function by converting the input from a string to a number. I have tried a variety of different settings in fiddler the onload, no wrap in body. I have changed the code a multitude of times. I could do it in jQuery but I really want just plain vanilla JavaScript.
First your input variable is not instantiated. I'm surprised that passed muster. Here's a bit on that.
So, where to get the initial value? Since a p tag doesn't have a value property, I'm pulling the p tag id'd as input, retrieving the innerHTML property, and running the result through parseInt.
Also, pull document.getElementById into your function so the button will have what it needs each time it's called.
And finally, sum was summed but not assigned to your output.
JSFiddle
(function () {
var doubleButton = function () {
var inputEl = document.getElementById("input");
var inputVal = inputEl.innerHTML;
var input = parseInt(inputVal, 10);
var sum = input + input;
inputEl.innerText = sum;
}
var boom = function () {
alert("BOOM!!!!! Dont you know you should never press the big red button")
}
document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
document.getElementById("btnRed").addEventListener("click", boom, false);
}());
Try this:
(function () {
var inputEl = document.getElementById("input");
var doubleButton = function () {
var sum = 0;
input = Number(inputEl.textContent);
sum = input + input;
inputEl.textContent = sum;
}
var boom = function () {
alert("BOOM!!!!! Dont you know you should never press the big red button")
}
document.getElementById("btnAdd").addEventListener("click", doubleButton, false);
document.getElementById("btnRed").addEventListener("click", boom, false);
}());