'how to grab an input in an html file and grab it from javascript file to

I have the following set up in html

<input maxlength="1" type="number" min="1" max="4" id ="c0r0"></input>

this has a text box where I can select a number 1 to 4 if I select a number I want it in my js file as a variable

I have tried this in my js file:

var tt = document.getElementsByTagName("input")[0].value;
console.log(tt);

I need it tt var be equal to the input. Do I need to add a button to submit my input? or once I select 1 through 4 my js file can grab the value



Solution 1:[1]

Below are the two simples ways of doing this.

Method 1:

Attach a change event listener to the input element i.e. a function that's called every time the value changes. Then use the target property of the event to get the value. For more details read this onchange event

Method 2

Get the html element reference using the getElementById (read more) and then use the that element to access the value.

Note: Using getElementById is easy and simple as you get the target element while other methods return a collection and you will have to find the element of concern in the collection.

Below is a small demo of the above recommended methods

function getValue(event) {
  // Method 1
  var val = event.target.value
  console.log('first box:' + val);
}

function method2() {
  // Method 2
  val = document.getElementById('c1r1').value;
  console.log('second box:' + val)
}
<input maxlength="1" type="number" min="1" max="4" id="c0r0" onchange="getValue(event)" />

<input maxlength="1" type="number" min="1" max="4" id="c1r1" onchange="method2(event)" />

Solution 2:[2]

You can try and Change :

<input maxlength="1" type="number" min="1" max="4" id ="c0r0"></input>

To :

<input maxlength="1" type="number" min="1" max="4" id="c0r0" />

Solution 3:[3]

I would like to point out these two things

  1. <input type="number"> elements are not really made for "selecting" values. Although you can of course use some autocomplete library to help you with that. A <select> element is probably the more natural choice for the task.
  2. The variable you desire can be easily set up. In fact I would suggest to create a const instead:
const tt=document.querySelector("input");

// the "variable" you require is then tt.value:

console.log(tt.value)

In a "real" application you should probably use a more specific CSS selector, like a class or an identity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manish
Solution 2 Almost
Solution 3