2

I'm writing a feature on a online electrical appliance shop. I've got the current order modeled, but got some problems with this Javascript code. It's supposed to change the color on an input if the real stock (on a database, what is controlled by the /api/GetStockArticle servlet) is lower than the current number on an input. I'm adding this event to all the inputs that i can have, which are dynamic, as it depends on the number of lines that my current order has.

    window.onload = function () {
        var inputs= document.getElementsByClassName("quantity");
        for (var i = 0, n = inputs.length; i < n; i++) {
            inputs[i].addEventListener("change", getStock, false);
        }
    }
        function getStock(evt) {
            $.ajax("../api/GetStockArticle", {
                data: {'cart': evet.target.id},
                dataType: 'text',
                cache: false,
                success: checkStock,
                error: function (xhr, status, ex) {
                    alert("Error (" + xhr.status + "):" + status);
                }
            });
        }
        function checkStock(stock) {
            //var input = document.getElementsByClassName("quantity");
            if (stock < input[0].value) {
                input[0].style.color = "#C02C11";
            } else {
                input[0].style.color = "black";
            }
        }

My main problem here is that, inside the checkStock function (which is the success function) i want to refer the same input which value changed, and i've got no idea on how to do that. Am i not properly guiding my code?

1 Answer 1

1

At first prepare your function to take the input as a parameter:

function checkStock(input, stock) {
  if (stock < input.value) {
      input.style.color = "#C02C11";
  } else {
      input.style.color = "black";
  }
}

And then just bind it when passing it as a callback:

success: checkStock.bind(null, evt.target)

Alternatively you could use currying or you could make use of the scope and closures:

function getStock(evt) {
        const input = evt.target;

        $.ajax("../api/GetStockArticle", {
            data: {'cart': evet.target.id},
            dataType: 'text',
            cache: false,
            success: function(stock) {
              if (stock < input.value) {
                input.style.color = "#C02C11";
              } else {
                input.style.color = "black";
              }
            },
            error: function (xhr, status, ex) {
                alert("Error (" + xhr.status + "):" + status);
            }
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.