How to use the Oninput attribute?

Asked

Viewed 1,593 times

1

I’m remembering some things in HTML and I came across the attribute Oninput. I know this attribute is used to make calculations, but I don’t know how to use.

2 answers

3

The OnInput is not an element but an attribute/event that fires when the user enters something within an element (it can be the element <input>).

Example:

<input type="text" oninput="minhaFuncao()">

The above code executes minhaFuncao() when someone writes something on it.

Another detail is that to create a function to be used in the element, you must study Javascript or jQuery.

  • I know it’s an attribute, my mistake. Thanks for the answer.

-1

oninput is an inappropriate way to add event listener to the event input. addEventListener is a preferred way. The event itself occurs when the value is changed. It is one of the three commonly used events for user input.

demonstração

// on every value change
document.querySelector("input").addEventListener('input', function (e) {
  console.log("input:", e.target.value)
})

// on blur if value was changed
document.querySelector("input").addEventListener('change', function (e) {
  console.log("change:", e.target.value)
})

// on every blur
document.querySelector("input").addEventListener('blur', function (e) {
  console.log("blur:", e.target.value)
})
<input>

// on every value change
document.querySelector("input").oninput = function (e) {
  console.log("input:", e.target.value)
}

// on blur if value was changed
document.querySelector("input").onchange = function (e) {
  console.log("change:", e.target.value)
}

// on every blur
document.querySelector("input").onblur = function (e) {
  console.log("blur:", e.target.value)
}
<input>

function onEveryValueChange(e) {
  console.log("input:", e.target.value)
}

function onBlurIfValueWasChanged(e) {
  console.log("change:", e.target.value)
}

function onEveryBlur(e) {
  console.log("blur:", e.target.value)
}
<input
  oninput="onEveryValueChange(event)"
  onchange="onBlurIfValueWasChanged(event)"
  onblur="onEveryBlur(event)"
/>

  • Could explain what you did and what the relationship of your code to the attribute is oninput?

  • @Andersoncarloswoss, okay

  • 1

    But why it is not recommended to use it?

  • @Andersoncarloswoss, as the element may have only one listener of the event input added via oninput and in case of adding it in html, the handler should be a global function. Also addeventlistener is more flexible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.