skip to Main Content

I want to make input box
um..

I started JS this week.. why it fires twice? plz help me :)..

if I press 1 , 2 , 3 , Just log will be 1, 2, 3..

const myForm = document.querySelector('#my-form')
const myArea = document.querySelector('#text-A')

myArea.addEventListener('keydown', function(a) {

  myForm.addEventListener('input', function(a) {
    console.log(a.currentTarget)
  })

  if (a.which == 13) {
    if (!a.shiftKey) {
      a.preventDefault();
    }
  }
})
<html>

<head>
  <link rel="stylesheet" href="test.css">
  <script defer src="test.js"></script>
</head>

<body>
  <form id="my-form">
    <textarea type="submit" id="text-A" name="text-A"> </textarea>
  </form>
</body>

</html>

2

Answers


  1. You are using input event listner inside keydown event, Every time keydown event trigger you are registering another event listner.

    const myForm = document.querySelector('#my-form')
    const myArea = document.querySelector('#text-A')
    
    myArea.addEventListener('keydown', function(a) {
    
      if (a.which == 13) {
        if (!a.shiftKey) {
          a.preventDefault();
        }
      }
    })
    
    myForm.addEventListener('input', function(a) {
      console.log(a.data)
    })
    <html>
    
    <head>
      <link rel="stylesheet" href="test.css">
      <script defer src="test.js"></script>
    </head>
    
    <body>
      <form id="my-form">
        <textarea type="submit" id="text-A" name="text-A"> </textarea>
      </form>
    </body>
    
    </html>
    Login or Signup to reply.
  2. Do not nest your addEventListeners and do not call addEventListener in an event that can repeat, for example when clicking a button.

    textarea type="submit" is also incorrect. You can have
    <input type="submit", <button type="submit" and <input type="image" which is also a submit, but not <textarea type="submit"

    Here is how to submit a form when pressing enter but not shift-enter in a form with only one field

    const myForm = document.querySelector('#my-form')
    const myArea = document.querySelector('#text-A')
    
    myArea.addEventListener('keydown', function(e) { // we use e for event
      if (e.key === 'Enter' // we can use better names when using event.key
        && !e.shiftKey) myArea.form.submit(); // submit if enter but not shift-enter
    })
    myForm.addEventListener('input', function(e) {
      console.log(e.currentTarget.id)
    })
    <form id="my-form">
      <textarea id="text-A" name="text-A"></textarea>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search