用户键入时从输入字段中删除字符(keyup)

时间:2017-04-24 14:47:18

标签: javascript jquery

当用户在字段上输入时,我正在寻找js或jq方法来删除#字符。

我试过了:

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

我可以看到"测试"在控制台中打印,但这对字段中的字符没有影响;它不会删除#。怎么做到这一点?

2 个答案:

答案 0 :(得分:10)

问题是因为您没有设置input的值,只是获取它并进行替换并对结果字符串不执行任何操作。试试这个:



$(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" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
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;
    }
}
&#13;
<input typpe="text" id="customerName" onkeyup="validateCustomerName();" />
&#13;
&#13;
&#13;