duckmike
duckmike

Reputation: 1036

Replace all commas in a string with JQuery/Javascript

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(",", "") 
  })
});

Upvotes: 13

Views: 53471

Answers (3)

totallyNotLizards
totallyNotLizards

Reputation: 8559

$(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.

Upvotes: 35

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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

Upvotes: 2

sp00m
sp00m

Reputation: 48807

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

Upvotes: 5

Related Questions