Search code examples
jquerykeyevent

keyup function with form submit


I have a function where I have a keyup on my textbox. Once I hit the "S" key and the form will submit. But the problem is, whenever I press the "S" key, it adds to the textbox and it is included in the textbox value and it is submitted. How can I avoid it when pressing "S", it should not be included in the textbox. Just do the submit without S value in textbox.

As you can see here in my image, there's a "S" on the last value. My target is to avoid that whenever I'm submitting my form using "S" key.

enter image description here

Thank you

     $(document).ready(function() {
    $('.btnsub').keyup(function(event) {
        if (event.which === 83)
        {
            event.preventDefault();
            $('#insertEntryy').click();
            console.log('1');
        
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="blabla">
<input type="text" class="btnsub">

<button id="insertEntryy" type="button">
asd
</button>
</form>


Solution

  • Add a keydown handler which prevents 's' from being added:

    $('.btnsub').keydown(function(event) {
        if (event.which === 83)
        {
            event.preventDefault();  
        }
    });
    

    So your whole script becomes:

    $(document).ready(function() {
        $('.btnsub').keyup(function(event) {
            if (event.which === 83)
            {
                event.preventDefault();
                event.stopPropagation();
                $('#insertEntryy').click();
                console.log('1');
            
            }
        });
    
        // New handler:
        $('.btnsub').keydown(function(event) {
            if (event.which === 83)
            {
                event.preventDefault();
            
            }
        });
    });