aturon
aturon

Reputation: 81

Can I pass an HTML element to a function defined in the oninput attribute directly from the HTML?

I'm working on a function called quantityLimits() that I'd like to reuse and call multiple times depending on the element passed to it.

One of these elements is this input number element in my HTML:

<input id="quantityInput" type="number" min=1 max=100 value=1 oninput="quantityLimits()">

This is the quantityLimits() function in Javascript that I have now:

function quantityLimits() {
  let max = parseInt(this.max);
  let quantity = parseInt(this.value);
  if (quantity > max) {
    this.value = max;
  }
  else if (quantity < 1) {
    this.value = Math.abs(this.value);
  }
}

This function prevents the user from entering a negative value in the input box and from inputting a number that is greater than the defined max value, which in my case is 100. Is it possible to pass the input element object in the element's oninput attribute such that I can use "this" in the quantityLimits() function to reference that object.

Something like this:

<input id="quantityInput" type="number" min=1 max=100 value=1 oninput="quantityLimits(***quantityInput***)">

Upvotes: 2

Views: 1229

Answers (1)

aturon
aturon

Reputation: 81

With Pooshonk's input, the answer is solved.

HTML:

    function quantityLimits(element) {
      let max = parseInt(element.max);
      let quantity = parseInt(element.value);
      if (quantity > max) {
        element.value = max;
      }
      else if (quantity < 1) {
        element.value = Math.abs(element.value);
      }
    }
 <input id="quantityInput" type="number" min=1 max=100 value=1 oninput="quantityLimits(this)">

Upvotes: 2

Related Questions