2

How can I take a number a user has entered into an HTML form and save it as a javascript variable that can be used throughout the entire javascript document?

For example, a user enters "8", presses enter, which will then be recorded as a variable called "input" that can be used by any subsequent javascript:

// How to get input value entered from user?

var triple = input*3

console.log(triple);
1
  • One way to achieve is use document.selector and target desired input and get value from it. Commented Dec 16, 2018 at 3:52

6 Answers 6

1

To acquire input via an HTML input field, you could do something like the following:

var triple;

document.getElementById('input').addEventListener('keyup', event => {
  
  // When user presses the enter key, then we update triple based on the 
  // current value of the input
  if(event.keyCode === 13) {
    
    triple = parseInt(event.currentTarget.value) * 3;
    console.log(triple)
  }
});
<input id="input" />

Here, an event listener is registered with the input element to detect keyup events. When the user presses the enter key (ie event.keyCode === 13), then the triple variable is updated based on the value entered into that input by the user.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. Nothing happens when I press "enter". I know your code is right so it has to be something wrong on my end. However, I copied the code exactly as is. The only difference is that I put the <input id="input" /> in a long html file. There aren't any errors in the console either... Do you know what I might be doing wrong here?
is it possible to put the "console.log(triple)" outside the documet.getElementById where "input" is 3, and 9 is logged to the console? Right now it is nested inside.
Yes it certainly is however I just put the console.log inside the event handler so that the updated value is written to console when its value is changed. Did you need something different to this?
Nevermind, I just realized it doesn't really matter because I can add any code I want into the "if" anyways. Silly me.
1

If you are looking to create a global variable, then you can do so using var. MSDN defines the scope of var as "The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value."

All you have to do is declare the variable input outside any function or object block. Here is my JSFiddle

var globalVar = 5; //global variable
var f1 = function() {
	var inpt = document.getElementById('myInput');
  console.log('input value = ' + inpt.value);
  console.log('globalVar value inside f1 = ' + globalVar);
}
f1(); //function call

var f2 = function() {
	globalVar = globalVar + 1;
	console.log('globalVar value inside f2 = ' + globalVar);
}
f2(); //function call
<input value="10" id="myInput">

Comments

1

Your question is a bit confusing, however based on my understanding of your question -

If you want to read value entered in a HTML text, in java script code use below -

         <html>
         <body>
         <script language="javascript" >

          function click_me()
          {
             var x=document.getElementById("numberInput").value;
             alert(x);
           }

        </script>

         Enter a number <input type="text" id="numberInput">
         <button onclick="click_me()">Click me</button>
         </form>
         </body>
         </html>

1 Comment

Sorry about that, I'll try to explain more clearly. If a user were to enter "8" in an html form. How would I take that 8 and save it to a variable that can be used in a javascript file?
0

A simple way to achieve what you require might be via the prompt() method. This causes the browser to display a simple input dialog from which you can acquire user input and store that in the input variable like so:

var input = prompt(); // This causes a input dialog to be display. If the user clicks ok, 
                      // then the result of prompt() is the value entered by the user
var triple = input * 3;

console.log(triple);

2 Comments

This is certainly a roundabout way of achieving this.. but I was hoping to get the user input from html.
@Ayma I see - here's a solution that demonstrates that: stackoverflow.com/a/53799335/8526705
0

Just add a prompt to create a con at the top of your JavaScript code:

const input = parseInt(prompt("Enter a number: "));

And now you can do whatever you want:

const input = parseInt(prompt("Enter a number: "));
var triple = input * 3;
console.log(triple);

Comments

0

There are multiple ways you can get user input in javascript.

  • Using prompt(). Prompt is a function will allows you to bring up a dialogue box which from that you can enter text, numbers, etc... The text you enter as an argument will act as the heading of the pop-up alert.

Take a look at the snippet below for an example:

let input = prompt("Enter a number:"); // Input in string format
let triple = input * 3; // Convert string to integer by using * operation
console.log(triple);

  • Another way you can retrieve user input is through HTML input elements. There are a number of different types of input elements which you can use such as password, number, date, text, etc... For your question, you would want to use a number input. You can create a number input like so in HTML:
<input type="number" id="number" value="0" />

Here the type attribute specifies that we will be entering a number as our input. The id attribute provides us with a way to refrence this input element in javascript so we can latter retrieve the number enter into it. And the value attribute is an optional attribute which specifies the default value of the input box.

When working with input boxes you need to specify when javascript should check the input box for a value. You can do this by adding an event listener so that your javascript will run a section of code everytime the user enters a number. Here is an example of adding an event listener to our number input box so that it triggers which the number in it changes:

document.getElementById('number').addEventListener('keyup', function(e) {/* do code */});

In the above line, we are referencing the input box via its id (number) and adding an input event listener to it.

Using this event listener we can then use the this keyword inside the function to refer to the input box itself. This allows us to do this.value to get the value of the number entered. Here I have also use e.keyCode to detect which key was pressed. If the keyCode is equal to 13 (ENTER) then the code will log the result, otherwise (else) it will do nothing.

See working example below:

document.getElementById('number').addEventListener('keyup', function(e) {
  if(e.keyCode == 13) { // Check if enter key pressed
      let triple = this.value * 3; // Get value of text box using this.value
      console.log(triple);  
  }
});
<input type="number" id="number" value="0" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.