Enter variable name in textbox and get corresponding value - javascript

I have created 3 variables a,b,c. I have assigned values to a and b and have also made a textbox. What I want to do is enter the name of a the variable in the textbox and click the button, then the textbox should should display the value assigned to that variable. It maybe very simple but I do not know what I did wrong.
Here is the FIDDLE
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=c;
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
​

Your easiest choice would be to assign your variables to a object, like this:
var vars;
function display() {
var value = document.getElementById("b1").value;
vars = {
a: 2,
b: 3,
c: value
}
if (vars.hasOwnProperty(value)) { // If the entered value is a variable name
document.getElementById("demo").innerHTML = vars[value]; // Display the variable
} else { // Otherwise
document.getElementById("demo").innerHTML = value; // display the value
}
}
Working example
The if/else can be replaced with this, to make it a little shorter:
document.getElementById("demo").innerHTML = vars.hasOwnProperty(value) // If
? vars[value] // Then
: vars.c; // Else

Try this way:
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
if(c==a){
document.getElementById("demo").innerHTML='a';
}
if(c==b){
document.getElementById("demo").innerHTML='b';
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update value.</p>
</body>
</html>
DEMO

What you are looking for is the eval() method (Which, do a quick google search, it is not recommended).
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=(eval(c));
// if user enters b in the input field, then the html in demo will be 3
// if user enters a in the input field, then the html in demo will be 2
}
</script>
Again, not recommended!

If you declare variables directly in you script-element they are created as properties of the window-object and can be accessed as such. Thus just update your script like the following to show the contents of the variables:
<html>
<head>
<script>
var a = 2, b = 3;
function display() {
var strVarName = document.getElementById('b1').value;
if(window.hasOwnProperty(strVarName)) {
document.getElementById('demo').innerHTML = window[strVarName];
} else {
document.getElementById('demo').innerHTML = 'Variable ' + strVarName + ' does not exist.'
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
This won't work if you declare the variables inside the display function, but this doesn't seem like a thing you would do if this code were to be used in a system to anything beside this one simple function.

Related

How do i get input from body

I am trying to make a code that takes in input from the body directly and prints it in real-time on the body as well. But what happens is when I actualy type on the body (meaning in mid-air) it registers that i've typed something and the hello disappears but instead of showing what i've typed it gives me undefined in it's place. Here's the code:
<body id="bod" onkeypress="keypres()">
<h1 id="txt">hello</h1>
<script>
function keypres(){
var x = document.getElementById("bod").value;
document.getElementById("txt").innerHTML = x;
}
</script>
</body>
You have to follow code below
<body id="bod" onkeypress="keypres(event)">
<h1 id="txt">hello</h1>
</body>
<script>
function keypres(event){
if(event.charCode=='32'){
document.getElementById("txt").innerHTML = event.key;
}
else{
document.getElementById("txt").innerHTML += event.key;
}
}
</script>

Declaring variables and using getElementById to print Hello World

The assignment is such that I have to declare variables 1(Hello), 2(world) and result, and create a string in p element using getElementById/innerHTML. The result should also printed in console log. I've tried several combinations such as this, but I have no idea how to go from here.
<!DOCTYPE html>
<html>
<body>
<p id= "tulos">Haloo maailma!</p>
<script>
var tulos = document.getElementById("tulos").innerHTML "Haloo";
var tulos = document.getElementById("tulos").innerHTML = document.getElementById("tulos").innerHTML+ "maailma!";
console.log(tulos);
</script>
</body>
</html>
im not sure what do you need, but my guess is you want to print variable to a p tag and also able to console it
<p id="target"></p>
<script>
let var1 = 'hello';
let var2 = 'world';
let result = var1 +' '+var2;
let target = document.getElementById('target');
target.innerHTML = result;
console.log(result);
</script>

Function does not change a var as I thought it would

I am trying to make a simple function that increases the number value of one variable by the value of another variable.
( a = 2 ) ( b = 5 ) ( a = a + b )
document.write(a) gives ( 2 ), which is ( a ) but unchanged. I expected to get ( 7 ). What am I doing wrong?
var a = 2;
var b = 5;
function add() {
a = a + b;
}
document.write(a)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) write before add function calls so no change. You need to update the element in the inside function
You need to add an HTML element to show your data and use innerHTML to set it
var a = 2;
var b = 5;
function add() {
a = a + b;
// instead of document.write, find the element that you want to hold your element
// and set it's inner html to your value
//this will update the DOM
document.getElementById("myHeader").innerHTML = a;
}
<input type="button" value="add" onclick="add()">
<!-- add an element to hold your result -->
<h1 id="myHeader">Hello World!</h1>
Make the neccsary changes in the code,
You have to write the document.write() at the time you make the function call .
In your case : You wrote it in body so whenever the page load at that time it takes the inital value of a and when you make the function call , the value of a get increased but not print .
<!DOCTYPE html>
<html>
<head>
<script>
var a = 2;
var b = 5;
function add() {
a = a + b;
document.write(a)
}
</script>
</head>
<body>
<div>
<script></script>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) function call is only run the first time the page loads. when you click the button, that only runs the add() function but does not rerun document.write(a)

Javascript - basic programing, can´t change picture

I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one

How can I change global variables in javascript?

My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?
var a = 5;
var b = 16;
var c = 27;
function reset(){
a = 0;
b = 0;
c = 0;
}
My html code to call the function:
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
</form>
</html>
Javascript code to show the variables:
function display(){
document.write("A is equal to " + a + "<br/>");
document.write("B is equal to " + b + "<br/>");
document.write("C is equal to " + c );
}
Html to display the variables
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
</form>
</html>
change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.
http://www.w3schools.com/jsref/met_form_reset.asp
There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.
That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:
var a = 5;
function reset() {
console.log(window.a); // 5
window.a = 10;
}
reset();
console.log(a); // 10

Categories