skip to Main Content

Am Just accepting only alphanumeric in Text field so i wrote this below code,

This works fine but some times its not working when onlyAllowAlphanumeric called several time

function onlyAllowAlphanumeric(obj) {
    
    obj.value = obj.value.replace(/[^a-zA-Z0-9 _]/g, '');
    console.log(obj.value);
};

$(document).on("keyup", "#fgCode, #sfgCode,#npdPlant ,#plant", function (e) {
    onlyAllowAlphanumeric(this);
});

Is there any other way or any other function to overcome this issue .

need keypress/keyup function to not allow only alphanumeric not even space should be accepted
please help me out

2

Answers


  1. This should do the job for you on single input

    <input onkeydown="return /[a-z]/i.test(event.key)" >
    Login or Signup to reply.
  2. Try binding <input> to the "input" event. then use .replace() with the RegExp of /[^A-Za-z]/ which means replace anything but letters.

    $(".alpha").on("input", alphaFilter);
    
    function alphaFilter(e) {
      let data = $(this).val();
      $(this).val(data.replace(/[^A-Za-z]/g, ""));
    }
      
    <input class="alpha" type="text">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search