How do you add a input element to a variable - javascript

I input a number into a textbox.
I want to know how do you cast this number to a declared variable:
For Example:
<body>
Please Enter value number 1: <input type = "text" id = "value1"></input>
<button onclick = "Display()">Display</button>
<p id = "Paragraph"></p>
<script>
The Question is here:
var a = document.getElementById("value1").value;
The statement above is what i want to know to do.
function Display()
{
document.write(a);
}
</script>
</body>
I am new to javascript, and i'm trying to learn so sorry if the question is a bit basic but im struggling to get this right.

I guess you mean something like this:
function Display()
{
var a = document.getElementById("value1").value;
document.getElementById( 'Paragraph' ).innerHTML = a;
}
With your code the variable a is just assigned, when the script is executed the first time. It is not a pointer to the value, but just grabs the value once. So if you want to use it, when clicking the button, you have to get it inside the executed function.
Don't use document.write() like this. If you want to display something at runtime innerHTML is a better choice!

Assign a inside your function:
function Display()
{
var a = document.getElementById("value1").value;
console.log(a);
}
Also, <input /> tags do not require a closing </input> tag.

Related

Make Function with querySelectAll with forEach

I want to create a javascript querySelectAll with foreach. I need to use this many times. So i want to create a function. But not working. Please help me.
<p id="o">one</p>
<p id="o">two</p>
<script>
function q(x,y) {
document.querySelectorAll(x).forEach(e => { e.y })
}
q('#o', innerHTML = 'Working');
</script>
If you want to put some code in a reusable form that you can pass around then it needs to be a function.
An expression is just going to be evaluated immediately.
innerHTML = 'Working' will assigned the string to the global variable innerHTML and then the pass the result (the string) to y.
You need it to be a function and then you need to call it.
What's more: An ID must be unique in a document. If you want to loop over a group of things then use a class.
function q(x, y) {
document.querySelectorAll(x).forEach(y)
}
q('.o', (element) => element.innerHTML = 'Working');
<p class="o">one</p>
<p class="o">two</p>

assign the value of `input ` to a variable but return blank in JS

I want to assign the value of input to a variable in Javascript, but I am not sure why the value of input is always blank.
Here is an example:
let input = document.getElementById('input').value
let val = 'not'
function check() {
//console.log(document.getElementById('input').value) will work
console.log(typeof input)
console.log(input)
}
<input id='input' type='text'>
<button onclick='check()'>Check</button>
The input value is blank (nothing), but the typeof input is string.
If I use document.getElementById('input').value, this will totally work which will display the value of input sucessfully.
Could anyone explain me a little bit why I assign it to a variable won't work?
Thanks for any responds!
Variable assignment val = 'not' takes place at the first time page load. When you need to assign dynamic value, like on a button click, you need an event handling mechanism (In your case, a click event). You are calling a function upon click, but not assigning any value to your variable there. Make assignment inside function like:
function check() {
val = document.getElementById('input').value
console.log(val)
}

Can't execute function in javascript

I've looked a lot in this website for an answer and honestly I've seen many close answers to my problem but still can't make it work.
I want to use a input textbox value and put it in javascript function then use javascript to calculate what I've given to the textbox for me and then put the answer to another paragraph in my html document (in this case I want to use kmh=ms*3.6 with return to do the calculation)
So this is my function code:
function msToKM() {document.getElementById('mstokm').innerHTML='<input type="text" name="mstokm" id="mstokmh" value="10"/>m/s<br><br><button type="button" class="buttons" onclick="convMSKM()" style="padding: 10px 10px;">Equals to!</button>';}
function convMSKM () {mstokm= document.getElementById('mstokmh'); mstokmA(mstokm);}
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
And I'm specificly having a problem with this part of the code:
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
because it's not executing the last part of it.
I can provide the html codes as well if needed.
How can I fix this?
Here's a demo how to do it
Well with onclick event i am selecting value of input field and than printing result in console. you can place it to any element you want instead of printing to console.
function handle(){
let val = document.getElementById('userIn').value;
console.log(3.6*val)
}
<input type='text' value='' id='userIn'/>
<button onclick='handle()'>calculate</button>
The return statement causes the function to stop executing, so what is happening is that you are returning value and it never gets to set that value inside the element. You can do something like this:
mstokmA(ms) {
document.getElementById('AmstokmA').innerHTML = ms*3.6;
}
OR more like you were trying to do:
mstokmA(ms) {
var kmh = ms*3.6; // set value inside variable
document.getElementById('AmstokmA').innerHTML = kmh; // append that value to the element
}
I prefer the first option.
I hope it helps ;).
Note: there is no need to return in this case.
Leave the return statement where it it, but replace "return" with "let".
Example:
function mstokmA(ms) {let kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}

Javascript: why will variable work locally but not globally

I am new to JavaScript and am having trouble understanding why a variable can be used when it is declared inside a function (locally) but not outside (globally).
For example: https://jsfiddle.net/Buleria28/kqu69aqt/
Or if it is easier to view here. Why will this work?:
function numDisplay (){
var e = document.getElementById("numVal").value;
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
And why won't this work?:
var e = document.getElementById("numVal").value;
function numDisplay (){
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
The corresponding HTML is:
<form method = "POST">
<fieldset>
<label for="numVal">Enter Number Value:</label>
<input type="number" id="numVal" name="numVal"/>
</fieldset>
</form>
I am curious because I would like to use the user input for found in the variable "e" in different functions.
In the case of:
var e = document.getElementById("numVal").value;
function numDisplay (){
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
e is computed at run time, so the value is nothing which is then stored as e (your starting value.)
However making a slight change to your code can make this work.
var e = document.getElementById("numVal");
function numDisplay (){
document.getElementById("show").innerHTML = e.value;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
In this example e's value is found on each click, which will then display the current value and set that as the innerHTML of your 'show' element.
The problem is when the script code runs. If you set a global variable like this and it is null
var e = document.getElementById("numVal").value;
Then it probably executed before the browser created that part of the page.
You can use global variables that you set to a number or string that way since that does not depend on the page / document:
var number_of_puffins = 11;
If you want a variable to point to a part of the document you need to have a function to set it after the page exists.
<body onLoad="setglobals();">
Be careful about using code like your example since the page can change if you add or delete items.
Both of your options work as planned.
The difference is the value.
When you run the script for the first time, there is no value in the input, but when you run it inside the function, it alredy has value.
You can change when you are calling the value, ie:
var e = document.getElementById("numVal"); //Remove the .value
/*why won't having the variable above rather than inside
the function work?*/
function numDisplay (){
//var e = document.getElementById("numVal").value;
document.getElementById("show").innerHTML = e.value; //use it here.
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
The function numDisplay() doesn't work correctly when e is a global variable because numDisplay() is triggered when #calcBtn is clicked.
Let's say you enter the number 5 in the input field and click the "Show Number" button. This runs numDisplay() and sets the HTML in #show to e. However, e never got the number 5. It still has an empty value which was assigned to it when you loaded the page. For it to keep getting new values each time you click the button, var e = document.getElementById("numVal").value; needs to be inside the function.

How to get value of JavaScript into HTML span?

If I have a much simplified JavaScript method such as this:
function myfunction() {
var i = 9;
}
Is there any way I can get the value of i into HTML such that when the web page with this method is called, the value 9 is displayed in a div or span element?
You can write document.getElementById("some ID").innerHTML = i
Hi :D you can try the following using JQuery:
var i = 9;
$('#spanId').text(i);
or the classic old-fashion way:
var tmp= document.getElementById('spanId');
tmp.textContent = id;
I hope this helps.
You can use innerHTML to embed the i value in a div or span element.
myfunction() current does not return its value. However, if you want to get the value when the page is "called" (loaded) you can do this:
function myfunction() {
var i = 9;
return i;
}
And in the markup:
<body onload="document.getElementById('id_of_your_div').innerHTML = myfunction()">
Please note that innerHTML has cross-browser issues, so you may want to use a library function such as jQuery's html() for reliable results.
Yes, you can assign an id to your <div> or <span> and set its innerText/textContent property to your value.
window.onload = function() {
var content = myfunction();
var tag = document.getElementById('displayVar');
if(typeof tag.innerText == "undefined") {
tag.textContent = content;
} else {
tag.innerText = content;
}
}
Do not use innerHTML if you do not want the HTML code of your value to be parsed (or if you don't expect any HTML value).
And no, you do not need a 31kb library to do that kind of work (just in case there's a bunch of "jQuery can do that!" answers).
Note that you must also modify myfunction() so that it returns the current value. A simple return i; statement in the function will do the trick.
JavaScript:
function myFunction() {
var i = 9;
return i;
}
$('myElement').innerHTML = myFunction();
HTML:
<span id="myElement"></span>
you can also use jQuery to simplify the syntax following are the three ways you can do that using jQuery,
1) $('span').text(i)
2) $('#someid').text(i) //someid = value of id attribute of span tag.
3) $('.someclassname').text(i) //someclassname = class name for the span tag.
Also using jQuery means forcing the users have to download addition jQuery lib when the page loads. That might slow down the page depending on the connection speed of the users. You might want to consider that while selecting between jQuery and plain JavaScript

Categories

Resources