Home > other >  how to change element function with js
how to change element function with js

Time:07-04

i have a <input type="text"/> which is to perform two functions. Which function is executed is to be decided via a button. This button should toggle the onkeyup function. For this I used the following:

document.getElementById('input-search-tags').onkeyup = filter_tagsC()

but when I click the button, the function will not change.

CodePudding user response:

To toggle between which function fires onkeyup you need a click event listener on the button to set which function needs to be run.

const input = document.querySelector("input")
const button = document.querySelector("button")

let functionState = "one"

const oneFunc = () => console.log("one")
const twoFunc = () => console.log("two")

input.onkeyup = oneFunc

const toggleFunctions = () => {
  if (functionState === "one") {
    input.onkeyup = twoFunc
    functionState = "two"
  } else {
    input.onkeyup = oneFunc
    functionState = "one"
  }
}

button.addEventListener("click", toggleFunctions)
<div>
  <input type="text" />
  <button>Toggle function</button
</div>

With this example, I get both elements with querySelector. Then I set a state value with let so that its value can be changed. Then I define the 2 functions I want to toggle between. I also set the input to have onkeyup of oneFunc, since the functionState starts as one.

Then I define a function that will assign a different function to onkeyup depending on the state of functionState and reset the functionState to the new value. Lastly, I add an event listener to the button to run the toggleFunctions function on click.

CodePudding user response:

You need to specify that you are calling a function onKeyUp and then specify that function's name:

document.getElementById('input-search-tags').onkeyup = function() {filter_tagsC()}

function filter_tagsC() {
    // Your Code Here.
}

For an an easier method of handling onkeyup, I would suggest looking at the keyup event listener method, as it is a bit more logical way of handling events. Hope this helps.

  • Related