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

前端 未结 3 1680
无人及你
无人及你 2021-01-25 07:31

I have to prevent Coldfusion\'s default list delimiter \',\' from being entered into a form input array. I am new to using javascript for validation purposes, and have never tri

相关标签:
3条回答
  • 2021-01-25 08:03

    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.

    0 讨论(0)
  • 2021-01-25 08:08

    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.

    0 讨论(0)
  • 2021-01-25 08:08

    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.

    0 讨论(0)
提交回复
热议问题