A.Martinez
A.Martinez

Reputation: 133

Javascript/AJAX current input on AJAX success function

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?

Upvotes: 2

Views: 44

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138477

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);
            }
        });
    }

Upvotes: 1

Related Questions