0

//why my console does not print when i give 2 input text field in the form ? whats the reason behind that?

        <input type="text" placeholder="name"> // one input text field in the form
       
    </form>
</body>
<script>
    let form=document.getElementById("form");
    form.addEventListener("submit",(event)=>{
        event.preventDefault();
        console.log("hello");// here hello is printing in console after press enter beacuse we have one text input field in form
    })
</script>
</html>

//with 2 input text field in form

<body>
    <form id="form">

        <input type="text" placeholder="name">
        <input type="text" placeholder="age">   // here 2 input fields were given to form 
       
    </form>
</body>
<script>
    let form=document.getElementById("form");
    form.addEventListener("submit",(event)=>{
        event.preventDefault();
        console.log("hello");// here hello is not printing after press enter why ? is this happening because we have 2 inpu fields inside form ? if it is , the how to solve this issue ?
    })
</script>
</html>
Rahul Mohanty
  • 342
  • 3
  • 9
  • 3
    A standard feature of forms is that, when there's only one input, enter will submit the form. When there's more than one, then submit button should submit the form as pressing enter on the first input will likely mean the second input has been forgotten/skipped/missed. I recommend you always have a submit button for the user to explicitly click when they are done as users tend to press enter too soon until they get used to working with web forms. – freedomn-m Sep 16 '22 at 06:05
  • thanks for your words . so as your knowledge if a form have more than one input field then i must have to add a submit button to submit the form . am i right ? is there any other way to submit the form when press "enter" with more than one input text field ? – Rahul Mohanty Sep 16 '22 at 06:34
  • You can add a keyup event handler and check if it's the enter key. If you add this to the *last* input only then you won't get the missing input when user doesn't realise enter will submit rather than "tab" to next input; but that's your UX call. This is how ye-olde-dumb-terminals worked, enter = tab. There used to be a lot of questions on how to make enter=tab. Similar solution. – freedomn-m Sep 16 '22 at 06:41
  • The linked answer suggests you can add `` then this will trigger/fire when you press enter. Much better than a keyup handler. – freedomn-m Sep 16 '22 at 06:43
  • yeah , its good to hear this solution !! much appreciated logic !! but with my knowledge its a bit complex to think and to do also !! – Rahul Mohanty Sep 16 '22 at 12:37

0 Answers0