简体   繁体   中英

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***)">

With Pooshonk's input, the answer is solved.

HTML:

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

Javascript:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM