0
let testTime = document.querySelectorAll(".testTime"); // this List has 3 value. 30, 60, 120
testTime.forEach((x) => {
    console.log(x.innerHTML);
    addEventListener("click", selectTime(this, x));
});

function selectTime(e, item) {
    e.preventDefault();
    
}

I want to define a parameter, after e parameter and e.preventDefault() for the function selectTime.

And I want to use item in selectTime

testTime.forEach((x) => {
    console.log(x.innerHTML);
    addEventListener("click", selectTime(this, x));
});

I use this keyword but It gave me an error

Uncaught TypeError: e.preventDefault is not a function
    at selectTime (time.js:20:7)
    at time.js:13:31
    at NodeList.forEach (<anonymous>)
    at time.js:11:10
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    This looks like it may be for a list of items where you select an option? Could a checkbox or radio button be closer to your use case? – Harrison Aug 06 '23 at 09:26

1 Answers1

0

Your logic and syntax is all wrong. You don't callthe event listener to anything in your forEach loop and you are calling selectTime the wrong way in the addEventListener function. addEventListener must be always called on some DOM element, and as the second argument you pass it a callback function which will be called after the click is fired. When you pass a callback function, you just pass the function definition, without parentheses. What you're doing now is calling the function. This is how the code should be properly structured

let testTime = document.querySelectorAll(".testTime");
testTime.forEach((time) => {
    console.log(time.innerHTML);
    time.addEventListener("click", (event) => {
        selectTime(event, time)
    });
});

function selectTime(e, item) {
    e.preventDefault();
    
}
IP002
  • 471
  • 1
  • 5
  • 17
  • 1
    you can just `time.addEventListener("click", selectTime);` the `item` will be available as the `event.currentTarget`. So `function selectTime(e){e.preventDefault(); const item = e.currentTarget; ...}`. Even better use [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation#:~:text=Attach%20an%20event%20listener%20to,occurs%20on%20a%20child%20element.) – pilchard Aug 06 '23 at 10:25