skip to Main Content

I am trying to trigger a keypress event when click left mouse button in an input tag with class name.
I can do with id but I don’t know how to trigger with class name.
How can I solve this?

I wanna trigger a keypress with class name.

3

Answers


  1. <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <input type="text" class="yourClassName" onkeypress="handleKeyPress(event)" />
        <script>
            function handleKeyPress(event) {
                if (event.key === 'Enter') {
                    console.log(event.target.value);
                }
            }
        </script>
    </body>
    
    </html>
    
    Login or Signup to reply.
  2. You can use "click" event and button code 0 for left press.

    const elements = document.getElementsByClassName("class-name"); //or use query selector
    
    for(const element of elements) {
      element.addEventListener("click", handleLeftClick);
    }
    
    function handleLeftClick(e) {
      if(e.button ===0) {
        //perform action
      }
    }
    Login or Signup to reply.
  3. To trigger keypress event using a class name you can use getElementsByClassName()

    let input = document.getElementsByClassName("input");
    input[0].addEventListener("keypress", function() { alert("the key is pressed") });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search