2

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?

Salexes
  • 187
  • 1
  • 2
  • 20
  • 1
    Possible duplicate of [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript) – gotnull Mar 06 '19 at 02:31
  • Thank you for the hint with the question. I do know that I need to use getElementById but how do I always get the latest input automatically if the enduser is changing the value? – Salexes Mar 06 '19 at 02:39
  • 1
    Have you thought about an event listener for keyup? – Elliot Mar 06 '19 at 02:42
  • @Elliot Thank you for your comment. Do you mind explaining a little bit more? I am still a beginner with javascript and I am not really familiar with it yet. Just started to learn it. – Salexes Mar 06 '19 at 02:44

6 Answers6

4

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" />
Aniket G
  • 3,471
  • 1
  • 13
  • 39
  • 1
    I did not know it was this easy to achieve! It really shows that I am still at a very beginner stage of learning javascript and jquery. Thanks a lot for the detailed explanations and the code snippets to test them! – Salexes Mar 06 '19 at 03:06
  • 1
    I just ran into this error: Cannot read property 'addEventListener' of null. As far as I understand that error could be caused because the script is already executed before the DOM finished loading. Is that correct ? If yes how to be sure it is executed after the DOM finished loading ? – Salexes Mar 06 '19 at 03:19
  • 1
    @Salexes it either means that the element you're trying to add an event listener on doesn't exist, or yes. The DOM hasn't loaded. I updated my solution. In this case, you should put `window.onload` before just like I did in the updated answer. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload, https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load – Aniket G Mar 06 '19 at 03:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189493/discussion-between-salexes-and-aniket-g). – Salexes Mar 06 '19 at 03:35
2

keyup() function ;)

It runs each time, when user types new text. Also, you can use input() or change() functions.

In jQuery it works like this:

$(document).on('keyup', '#InputID', function(){
    //...code...
    var discount = Number( document.getElementById('InputID').value )*10/100;
});
Bubu
  • 31
  • 5
1

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.

$('#code').keyup(function() {
    var discountcode = this.value;
    console.log(discountcode);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="code" type="test" />

Keyup runs every time a specific element is lifted. Imagine someone enters 'Hello'

You will see the following logged:

'H' 'He' 'Hel' 'Hell' 'Hello'

Elliot
  • 928
  • 10
  • 17
  • 1
    @AniketG I was elaborating on my comment and was still writing it up before I saw the answer below. Since it has a code snippet and was posted 2 minutes between each other, I don't think it's a big deal. – Elliot Mar 06 '19 at 02:56
  • you can keep it if you want. I just know the one thing I hate is seeing multiple answers (that are the same). As I have on every other occasion, I'm upvoting the one that went up first. Which was the other one – Aniket G Mar 06 '19 at 02:58
1

look at the code snippet. using JavaScript to get the values. and can use addEventListener to detect the change and use detectChange function to get the latest values.

var discount = [];

function detectChange() {
  var table = document.getElementsByClassName("shappify_qb_grid")[0];

  for (var i = 0; i < table.rows.length; i++) {
    var row = "";
    for (var j = 0; j < table.rows[i].cells.length; j++) {
      if (j == 1) {
        row = table.rows[i].cells[j].innerHTML;
        rate = parseFloat(row);
        if (rate && discount.indexOf(rate) < 0) {
          discount.push(parseFloat(row));
          console.log('---', parseFloat(row));
        }
      }
      // console.log('discount : ', discount);
    }
  }
}

detectChange();
console.log('discount : ', discount);
<table class="shappify_qb_grid" border=1>
<thead>
 <tr>
  <th>Qty</th>
  <th>Discount</th>
 </tr>
</thead>
<tbody>
 <tr>
  <td>Buy 1</td>
  <td>0% Off</td>
 </tr>
 <tr>
  <td>Buy 2</td>
  <td>10% Off</td>
 </tr>
 <tr>
  <td>Buy 4</td>
  <td>12% Off</td>
 </tr>
 <tr>
  <td>Buy 5</td>
  <td>14% Off</td>
 </tr>
 <tr>
  <td>Buy 6</td>
  <td>17% Off</td>
 </tr>
</tbody>
</table>
Shiv Kumar Baghel
  • 2,464
  • 6
  • 18
  • 34
  • Just to be sure I understand the code you posted correctly. If I would change the quantity input field to e.g. 4 it would automatically assoiate it with 12% discount? Still a javascript beginner so I just want to be sure to understand each step of the code – Salexes Mar 06 '19 at 03:10
1

This work for me!

document.getElementById("text").value;

<input id="text" />
David Buck
  • 3,752
  • 35
  • 31
  • 35
1

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';.

user4157124
  • 2,809
  • 13
  • 27
  • 42
Abel Nebay
  • 11
  • 1
  • The question is about getting the value, not changing the value. There are also answers from over a year ago that explain how to do this. – Barmar Oct 27 '20 at 19:36