Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from input field with Javascript?

How can I get the value of an specific input field with Javascript?

Lets take this shopify shop for example: https://geekymate.com/products/magic-doormat-1?variant=18941211607138

I am trying to create a script which is automatically applying an discount code based on the quantity filled in the quantity field.

But to do that I need to be able to get the latest value of the field. How would the code look like to get the latest/current value?

EDIT: Thank you for the hint with the question. I do know that I need to use getElementById ( For the linked page above it would be this: var x = document.getElementById("Quanity").value; ) but how do I always get the latest input automatically if the enduser is changing the value?

like image 430
Salexes Avatar asked Aug 11 '26 17:08

Salexes


1 Answers

The other answers are also correct (using jQuery .keyup), but you can also use this solution below (which is better). This solution uses pure javascript.

The code selects the element by using .getElementById() and uses .addEventListener() to do something when input changes.

var text = document.getElementById("text");
window.onload = function() {
  text.addEventListener("input", function() {
    console.log(text.value);
  });
}
<input id="text" />

Or you can use the following if you want a jQuery solution. This uses jQuery .bind().

$("#text").bind("input", function() {
  console.log($("#text").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="text" />
like image 67
Aniket G Avatar answered Aug 14 '26 08:08

Aniket G