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?
6
Answers
keyup()
function 😉It runs each time, when user types new text.
Also, you can use
input()
orchange()
functions.In jQuery it works like this:
It’s a Jquery function that runs on keypress. I’ve included a snippet below to see how it would tie in with an input field.
Keyup runs every time a specific element is lifted. Imagine someone enters ‘Hello’
You will see the following logged:
‘H’ ‘He’ ‘Hel’ ‘Hell’ ‘Hello’
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.Or you can use the following if you want a jQuery solution. This uses jQuery
.bind()
.look at the code snippet. using JavaScript to get the values. and can use
addEventListener
to detect the change and usedetectChange
function to get the latest values.This work for me!
Use the
document.getElementById();
-command to get the existence of the referenced element in your HTML page. Then use the same technique of assigning attributes in the original HTML coding rules.Use
document.getElementById('able').value = 'whatever';
.