Replacing characters with jQuery

I am trying to remove commas from all my text fields on a keyboard. I came up with a script below, but it does not work. Can anyone see what I'm doing wrong?

<script> $("input[type='text']").keyup ( function () { alert('1'); $(this).val($(this).val().replace(/[,]/g, "")); } ); </script> 

NOTE. please excuse $ in Script. SO will not let me publish it otherwise ...

+4
source share
5 answers

You might want to wrap the entire code snippet in the document ready function

 $(function() { $("input:text").keyup(function() { $(this).val($(this).val().replace(/[,]/g, "")); }); }); 

You can read all about it on the jQuery documentation site .

+13
source

As already mentioned, make sure you use $ (document) .ready () - http://api.jquery.com/ready/ . In addition, instead of replacing commas with keyup, you should disable them when you press a key, returning false:

 $(document.ready(function () { $("input[type=text]").keypress(function (evt) { if (String.fromCharCode(evt.which) == ",") return false; }); }); 

Example: http://jsfiddle.net/QshDd/

This gives a more professional feeling: "," is blocked without appearing, and then disappears when you release the key. However, like your solution, this will not copy and paste the commas into your input. To do this, you can connect to the onpaste or onchange event.

If you want to use keyup and replace, you really don't need to deal with jQuery wrappers, you can access the value property directly:

 $(document.ready(function () { $("input[type=text]").keyup(function (evt) { this.value = this.value.replace(/,/g, ""); }); }); 
+5
source

This works for me: http://jsfiddle.net/vsnrc/1/

+2
source
 <script> $(document).ready(function() { $("input[type='text']").live('keyup',function () { alert('1'); $(this).val($(this).val().replace(/[,]/g, "")); }); }); </script> 

If your entry is in the update panel or added after the binding occurs, this should work.

+1
source

try it

 <script> $("input[type='text']").keyup ( function () { alert('1'); $(this).val($(this).val().replace(',', "")); } ); </script> 
0
source

All Articles