On keypress event, how do I change a ',' to a '~'

时光总嘲笑我的痴心妄想 提交于 2019-12-02 03:34:10

I put your HTML on jsfiddle (you can test it there) and added this JavaScript, using a selector that matches all and elements:

$(document).ready(function(event){
    $(document).delegate("input, textarea", "keyup", function(event){
        if(event.which === 188) {
            var cleanedValue = $(this).val().replace(",","~");
            $(this).val(cleanedValue);
        }
    });
});

All commas in the value string are replaced by a tilde if a comma (code 188) was entered.

Remember that JavaScript validation is nothing you want to rely on. The commas can easily be send to the server or never get replaced, e.g. in a user agent with JavaScript disabled.

DefyGravity

I replaced the name[] .live() event.which = 126; to event.originalEvent.keyCode=126;

var regExComma = /,/;
$("[name='name[]']").live("keypress",function(event){
     if(regExComma.test(String.fromCharCode(event.which)){
       //this line works as expected. and will swap out the value on keypress.
       if(event.originalEvent.keyCode){
         event.originalEvent.keyCode=126;
       }else if(event.originalEvent.charCode){
         event.originalEvent.charCode=126;
       }
     }
});

wolfram I upped your keyUp solution as well.

Imho, there's no need to check those keyCodes:

 $(document).ready(function(event){
    $('#fieldName').keyup(function(event) {
        var cleanedValue = $(this).val().replace(",","~");
        $(this).val(cleanedValue);
    });
});

Check it on jsFiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!