13

I have a form where I have a couple hundred text boxes and I'd like to remove any commas when they are loaded and prevent commas from being entered. Shouldn't the follow code work assuming the selector is correct?

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value.replace(",", "")
  })
  .onkeyup(function () {
      this.value.replace(",", "") 
  })
});
5
  • Did you try the above code, and if so, what was the outcome? Commented Aug 21, 2012 at 13:00
  • nearly right, see this: davidwalsh.name/javascript-replace Commented Aug 21, 2012 at 13:00
  • I'd suggest using input event instead of keyup. Your protection can be overcome by pasting commas by rightclick->contextmenu->paste, which won't trigger keyup. Commented Aug 21, 2012 at 13:02
  • 1
    @Shyju Maybe it's some kind of spreadsheet? Commented Aug 21, 2012 at 13:02
  • Yes, it is some kind of spreadsheet. Keep praying Shyju. Commented Aug 21, 2012 at 13:24

3 Answers 3

36
$(function(){
    $("input[id*=_tb]").each(function(){
        this.value=this.value.replace(/,/g, "");
    }).on('keyup', function(){
        this.value=this.value.replace(/,/g, "");
    });
});

See here for an explanation and examples of the javascript string.replace() function:

http://davidwalsh.name/javascript-replace

as @Vega said, this doesn't write the new value back to the textbox - I updated the code to do so.

Sign up to request clarification or add additional context in comments.

2 Comments

the each could be replaced with $("input[id*=_tb]").val(function (_, val) { return val.replace(/,/g, ''); }), though it won't make much of a difference in this scenario.
one should most certainly use on('keyup', ... as onkeyup is no valid jQuery method. (see the comments on Vegas answer ;))
5

Use a regex with the g flag instead of a string: .replace(/,/g, "").

Comments

2

Your code looks right except that it is not setting the value back to the input field,

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value = this.value.replace(/,/g, "")
  })
  .onkeyup(function () {
      this.value = this.value.replace(/,/g, "") 
  })
});

Edit: Used regex

1 Comment

@duckmike You should track back on error stack to see where the error is triggered from your code..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.