Monday, May 20, 2024
137
rated 0 times [  139] [ 2]  / answers: 1 / hits: 18862  / 5 Years ago, wed, march 6, 2019, 12:00:00

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?


More From » data-extraction

 Answers
40

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 />




[#52476] Friday, March 1, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;