Home > Back-end >  keyup function with form submit
keyup function with form submit

Time:06-24

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" >

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

CodePudding user response:

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();
        
        }
    });
});

CodePudding user response:

If your input accepts only numbers, use Regex: /[a-zA-Z]/g and .replace() so you filter out letters. If you want everything but 's' Regex: /[sS]/g (Replacement filter for all letters is commented).

BTW, the form can't submit unless the <button> has type="submit" or no type at all (you probably already know that, but it needed to be said for future readers).

$(document).ready(function() {
    $('.btnsub').on('keyup', function(e) {
      const rgx = new RegExp(/[sS]/, 'g');
      // const rgx = new RegExp(/[a-zA-Z]/, 'g')
      if (rgx.test(this.value)) {
        this.value = this.value.replace(rgx,'');
      }
      if (e.key === 's') {
        $('#insertEntryy').click();
        console.log('clicked');
      }
      console.log(this.value);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="blabla">
<input type="text" >
<button id="insertEntryy" type='button'>
asd
</button>
</form>

  • Related