Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove character from input field while user is typing (keyup)

I'm looking for a js or jq way to remove # character while user is typing on a field.

I tried this:

$( function() {
    $( ".remove-sharp" ).on( "keyup", function( event ) {
        console.log( 'test' );
        $( this ).val().replace( /\#/, "" );
    } )
} );

I can see the "test" being printed in console but this has no effect on the characters in the field; it doesn't remove #. How to achieve this ?

like image 738
Robert Brax Avatar asked Apr 24 '17 14:04

Robert Brax


2 Answers

The issue is because you're not setting the value of the input, only getting it and making the replacement and doing nothing with the resulting string. Try this:

$(function() {
  $(".remove-sharp").on("keyup", function(event) {
    var value = $(this).val();
    if (value.indexOf('#') != -1) {
      $(this).val(value.replace(/\#/g, ""));
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="remove-sharp" />
like image 112
Rory McCrossan Avatar answered Nov 14 '22 23:11

Rory McCrossan


function validateCustomerName(){
    var validatedName = "";
    var restrictedCharactersArray = ["0","1","2","3","4","5","6","7","8","9","~","`","!","@","#","$","%","^","&","*","(",")","-","_",
        "+","=","{","}","[","]",":",";","'","<",">",",",".","?","/","/\/","|"];
    var customerName = document.getElementById("customerName").value;
    var numberValidation = (/^[a-zA-Z_ ]+$/g).test(customerName);
    if(!numberValidation){
        validatedName = "";
        var customerNameArray = customerName.split("");
        for(var i=0;i<restrictedCharactersArray.length;i++){
            var restrictedCharacter = restrictedCharactersArray[i];
            if(customerNameArray.indexOf(restrictedCharacter) !== -1){
                for(var j=0; j<customerNameArray.length; j++){
                    var customerNameCharacter = customerNameArray[j];
                    if(customerNameCharacter !== restrictedCharacter){
                        validatedName = validatedName+customerNameCharacter;
                    }
                }
            }
        }
        document.getElementById("customerName").value = validatedName;
    }
}
<input type="text" id="customerName" onKeyUp="validateCustomerName();" />
like image 38
Sudhindra Pai Avatar answered Nov 14 '22 23:11

Sudhindra Pai