tags:

views:

86

answers:

5

I'm trying to remove commas from all of my textboxes on keyup. I came up with the script below but it's not working. Can anyone see what I am doing wrong?

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

NOTE: please excuse the $ in Script. SO won't let me post it otherwise...

+4  A: 

You might want to wrap that whole chunk of code in a document ready function

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

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

jessegavin
+2  A: 

It's working for me: http://jsfiddle.net/vsnrc/1/

aularon
+1 for introducing me to jsfiddle. That's a niffty tool!
Abe Miessler
A: 

Try this

<script>
        $("input[type='text']").keyup
        (
            function () 
            {
                alert('1');
                $(this).val($(this).val().replace(',', ""));
            }
        );
    </script>
Maulik Vora
+2  A: 

As others have mentioned, make sure you're using $(document).ready() - http://api.jquery.com/ready/. Also, instead of replacing commas on keyup, you should disallow them on keypress by 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 feel, the "," is blocked without appearing and then disappearing when you release the key. Like your solution, however, this won't catch copying and pasting commas into your input. For that, you can hook into the onpaste or onchange event.

If you want to stick with keyup and replace, you don't really need to mess around with jQuery wrappings, you can access the value property directly:

$(document.ready(function () { 
    $("input[type=text]").keyup(function (evt) {
        this.value = this.value.replace(/,/g, "");
    });
});
Andy E
+1 for being the only answer to actually give OP a better way of doing what he's trying to do and not just say "wrap in `$(document).ready()`."
Josh Leitzel
@Josh: thanks :-) Alas, I fear the OP might have skipped my advice.
Andy E
+1 for a good answer. I agree with Josh.
jessegavin
+1  A: 
<script>
    $(document).ready(function()
    {
        $("input[type='text']").live('keyup',function () 
        {
            alert('1');
            $(this).val($(this).val().replace(/[,]/g, ""));
        });
    });
</script>

If your input is in an update panel, or added after the binding takes place, this should work.

Nico