Search code examples
javascriptjqueryonkeyup

Jquery: Split/Join String onKeyup Event


I am using a function to sanitize a string with the onkeyup event. The following code works ok:

<input type="text" id="username"  maxlength="15" onkeyup="this.value=sanitize(this.value)">

<script language="javascript" type="text/javascript">
    function sanitize(str) {
        return str.split(/[^a-z0-9._-]/g).join('');
   }
</script> 

I was wondering how to re-write the same code but using jquery. For some reason the following code doesn't fire the onkeyup event:

<input type="text" id="username"  maxlength="15">

<script language="javascript" type="text/javascript">
$(document).ready(function () {
        $("#username").keyup(function(){
        return $("#username").val().split(/[^a-z0-9._-]/g).join(''); //--> this line is not working
    }); 
});

Thanks in advance!


Solution

  • You've to set the value using val(). Also, there is no need of split() and then join(), use replace().

    $("#username").val(function(i, value) {
        return value.replace(/[^a-z0-9._-]/g, '');
    });
    

    $("#username").keyup(function() {
      $(this).val(function(i, value) {
        return value.replace(/[^a-z0-9._-]/g, '');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="username" maxlength="15" />

    I'll also suggest to use pattern attribute on input.

    <input type="text" id="username" maxlength="15" pattern="[a-z0-9._-]{0,15}" />
    <!--                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->