在按键事件中,如何将’,’更改为’〜’

我必须防止Coldfusion的默认列表分隔符’,’被输入到表单输入数组中。 我是新手使用javascript进行validation,并且从未尝试切换某人输入的值。我怎么能抓住一个逗号,并用tilda替换它?

Javascript我到目前为止尝试过:

$(document).ready(function(event){ var regExComma = /,/; $("[name='name[]']").live("keypress",function(event){ // i know i could check the numerical value, i feel this requirement can get more added to it and I would like to just change the regEx accordingly. if(regExComma.test(String.fromCharCode(event.which)){ //it was a ',' switch it to '~' event.which = 126; } }); // added to show that the 'name' input form array is the only input that cares about the ',' var regExDig = /[\d]/ $("[name=min[]],[name=max[]]").live(keypress, function(event){ if(!regExDig .test(String.fromCharCode(event.which)){ event.preventDefault(); $("#cfocFormMessages").trigger("updateMessages", {"url":"components.cfc/CFOC.cfc", "data":{"more":"stuff"}}); } }); }); 

cfml / html涉及:

 
name col min col max col edit
edit
add

如果我在一个JSON字符串 ?method = saveVersion改为 ,Coldfusion的典型响应如下:

 {VERSION:"",name:"name1,name2",min:"1,3", max:"2,4",id:"1,2"} 

我把你的HTML放在jsfiddle上 (你可以在那里测试)并添加这个JavaScript,使用匹配所有和元素的选择器:

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

如果输入了逗号(代码188),则值字符串中的所有逗号将替换为代字号。

请记住,JavaScriptvalidation不是您想要依赖的。 逗号可以很容易地发送到服务器或永远不会被替换,例如在禁用JavaScript的用户代理中。

我替换了名称[] .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我也提升了你的keyUp解决方案。

Imho,没有必要检查这些keyCodes:

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

在jsFiddle上查看它。