0

here i have a form with a text area.I had a keyup event attach to the text area.While giving input t o the text area with one finger i press down the key and with other hand i click the submit button.So the scenario is the form gets submitted while giving input to the text area.How can i prevent that from happening ?

<html>
<body>
<form action='sample.php' method='post'>
<input type='text' id='mytext' value=''>
<input type='submit' value='submit'>
</form>
<script>
document.getElementById('mytext').addEventListener('keyup',function(){
    console.log("keyup");
})
</script>
</body>
</html>
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    use validation and/or an `onsubmit` handler. – Daniel A. White Nov 03 '16 at 11:20
  • tried that...validation is used to check only numeric input...i can press and hold down any number key and submit the form as well – AL-zami Nov 03 '16 at 11:21
  • I don't know why? `keyup` event not trigger form submission.Then why & what you are ask to prevent that? [see the fiddle](https://fiddle.jshell.net/d558wrte/) – prasanth Nov 03 '16 at 11:26

2 Answers2

0

Assign true to a variable in the keydown event.

Assign false to it in the keyup event.

Test the value of it in the submit event and call preventDefault if it is true.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • can you please elaborate :\..so i need a global variable...that could create problem...i am trying to avoid globals – AL-zami Nov 03 '16 at 11:22
  • What don't you understand? Your code demonstrates that you know how to assign event handlers. Assigning a value to a variable shouldn't be difficult. What's the problem? – Quentin Nov 03 '16 at 11:22
  • You can use a closure / IIFE to avoid the use of a global. http://stackoverflow.com/a/1841941/19068 – Quentin Nov 03 '16 at 11:28
0

This will not allow submit for 3 seconds after last keypress. In your keyup event, you set canSubmit to false, and then set a timeout with setTimeout that waits 3000 milliseconds, and then sets the value back to true.

Then you add another event listener to the form, which checks if canSubmit is false, and calls event.preventDefault(), which ends the event there.

<html>
    <body>
    <form action='sample.php' method='post' id="myForm">
    <input type='text' id='mytext' value=''>
    <input type='submit' value='submit'>
    </form>
    <script>
    var canSubmit = true;
    document.getElementById('mytext').addEventListener('keyup',function(){
        canSubmit = false;
        setTimeout(function () {
            canSubmit = true;
        }, 3000);
    });
    document.getElementById('myForm').addEventListener('submit', function(e) {
        if (!canSubmit) {
            return e.preventDefault();
        }
    })
    </script>
    </body>
</html>
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66