1

I have a form that lists a remaining quantity of a product and below it an input field that lets you put a quantity into the form to submit for purchase.

I have the remaining quantity wrapped in a span with an ID. On keyup, I want to compare the value of the span with the input entered into the field.

If the input is greater than the value in the span, on keyup, I want to change the value of the input to 0 or the equivalent of the span ID value.

Here is my javascript I am trying to use to accomplish this:

<script>
$(document).ready(function () {
   document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);

    function Qty_check(){
        var QTY1check = document.getElementById('one_and_done_stool_QTY_check').value;
        var QTY1remain = document.getElementById('one_and_done_stool_QTY_remain').innerHTML;

        if (QTY1check.value > QTY1remain.innerHTML)
            alert("NOPE");
            {document.getElementById("one_and_done_stool_QTY_check").value = 0;}
    };}
</script>

And here is the html:

<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">
  • Could the value types are off? It looks like you are wanting the inputs numeric values and the types are actually strings. Try using Number, here: if ( Number(QTY1check.value) > Number(QTY1remain.innerHTML)) – Display name Apr 12 '18 at 17:13

1 Answers1

1

Your main issue is in this line:

document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);

You can rewrite:

document.getElementById('one_and_done_stool_QTY_check').onkeyup = Qty_check;

or you may use directly the input event:

document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);

or the jQuery way:

$('#one_and_done_stool_QTY_check').on('input', Qty_check);

The snippet:

document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);


function Qty_check(e) {
    var QTY1check = +document.getElementById('one_and_done_stool_QTY_check').value;
    var QTY1remain = +document.getElementById('one_and_done_stool_QTY_remain').textContent;

    if (QTY1check > QTY1remain) {
        console.log("NOPE");
        document.getElementById("one_and_done_stool_QTY_check").value = 0;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">
gaetanoM
  • 41,594
  • 6
  • 42
  • 61