How to Get a Number Value from an Input Field

How to get a number value from an input field?

You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle

You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.

function Calculate() {    var TotalProductionTime = document.getElementById("TotalProductionTime").value;    var TotalProductionTimeInMinutes = TotalProductionTime * 60;    var Breaks = document.getElementById("Breaks").value;    var Malfunctions = document.getElementById("Malfunctions").value;    var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;}
<form id="frm1" action="Calculate.html">    <table width="350px" border="1px">        <tr>            <th colspan="2">Availability</th>        </tr>        <tr>            <td>Total Production Time</td>            <td>                <input type="number" id="TotalProductionTime" placeholder="">hours</td>        </tr>        <tr>            <td>Breaks</td>            <td>                <input type="number" id="Breaks" placeholder="">minutes</td>        </tr>        <tr>            <td>Malfunctions</td>            <td>                <input type="number" id="Malfunctions" placeholder="">minutes</td>        </tr>        <tr>            <td>Theoretical production time:</td>            <td>                <p id="test"></p>            </td>        </tr>    </table>    <input type="button" onclick="Calculate()" value="calculate"></form>

How do I get the value of text input field using JavaScript?

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1

document.getElementById('textbox_id').value to get the value of
desired box

For example

document.getElementById("searchTxt").value;

 
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0],
for the second one use [1], and so on...

Method 2

Use
document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example

document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example

document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example

document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example

  • document.querySelector('#searchTxt').value; selected by id
  • document.querySelector('.searchField').value; selected by class
  • document.querySelector('input').value; selected by tagname
  • document.querySelector('[name="searchTxt"]').value; selected by name

Method 6

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example

  • document.querySelectorAll('#searchTxt')[0].value; selected by id
  • document.querySelectorAll('.searchField')[0].value; selected by class
  • document.querySelectorAll('input')[0].value; selected by tagname
  • document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support































































































































BrowserMethod1Method2Method3Method4Method5/6
IE6Y(Buggy)NYY(Buggy)N
IE7Y(Buggy)NYY(Buggy)N
IE8YNYY(Buggy)Y
IE9YYYY(Buggy)Y
IE10YYYYY
FF3.0YYYYN IE=Internet Explorer
FF3.5/FF3.6YYYYY FF=Mozilla Firefox
FF4b1YYYYY GC=Google Chrome
GC4/GC5YYYYY Y=YES,N=NO
Safari4/Safari5YYYYY
Opera10.10/
Opera10.53/YYYY(Buggy)Y
Opera10.60
Opera 12YYYYY

How can i get a input number value in javascript?

I believe you want to update the number when it changes. Consider adding an event listener to the input element. Such that it updates the number variable every time you change it's value.

const numberInput = document.getElementById("number");
let number = numberInput.value;

numberInput.addEventListener("change", (event) => {
number = event.target.value
console.log(number)
})
<input type="number" id="number" value="1" />

How can I get a number input value as a number instead of a string?

You can use jQuery's valHooks to change how jQuery returns values.

$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};

You only need to do this once in your code and then all type=number inputs will instead return a number.

console.log(
"num is a string",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)

$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};

// confirm no neffect on type='text'
console.log(
"num is a number",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='num' value="1">
<input type='text' id='txt' value="1">

How to get value from input type = number?

know that document.getElementsByClassName(...) returns a HTMLCollection regardless of whether there is only one element or more.

what you want is this:

var num = input[0].value;

note - typically, if you want to target only one element, you should use an id attribute on that element and then use document.getElementById(...) to retrieve the value of the element.

Getting the value from input element in typescript

If you are using an editor like VSCode to write Typescript, I've found the ability to inspect code very valuable in learning more about what's occurring in the typing system. In VSCode you can right click on the method(or type) and choose Go to definition.

Inspecting the method in your question, getElementById, you can see it returns an HTMLElement. This type doesn't have a value property on it. This makes sense as getElementById can return any HTMLElement on the page as long as it has an id attribute. Not every HTMLElement though has a value property(for instance a div/span/p, etc).

Since you know what type you are expecting, but the type system can't, to get this to work, you have to tell Typescript what type of element you expect to be selecting. You would do that through casting the type of the selected element as follows:
const inputElement = <HTMLInputElement> document.getElementById("food-name-val");
or
const inputElement = document.getElementById("food-name-val") as HTMLInputElement;

Now, since Typescript recognizes the selected element as an HTMLInputElement, it won't error when you access the value property on it.

In your case that would look like:
let foodName = (document.getElementById("food-name-val") as HTMLInputElement).value;

How to make HTML input tag only accept numerical values?

HTML 5

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>,
including various numeric filters. This will correctly handle
Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations,
non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purpose, you can have JS validation as below:

function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/

How to get value from an input field from a class of input fields?

var quantity = document.querySelectorAll('.quantity'); is not contain a single value. so you cannot change the value using .value it is like an array so you have to us indexing.

const overlay = document.querySelector('.overlay');
const overlayBtn = document.querySelector('.overlay-btn');
var quantity = document.querySelectorAll('.quantity');
var amtBtn = document.querySelectorAll('.amt-btn');

let getQuantity = []; // updated
overlayBtn.addEventListener('click', function(){
overlay.style.display = "block";
});

amtBtn.forEach(function(btn){
btn.addEventListener('click', function(e){
e.preventDefault();

// updated
for(let i = 0;i<quantity.length;i++ ){
getQuantity.push(quantity[i].value);
}

console.log(getQuantity);
});
});

Output

(4) ["3", "43", "43", "23"]
0: "3"
1: "43"
2: "43"
3: "23"
length: 4
__proto__: Array(0)

Get value of input type=number with JS when it contains non-numeric characters

This is what I was looking for:

$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});

I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3

However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to @int32_t for the suggestion.



Related Topics



Leave a reply



Submit