Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to remove spaces from a textbox value

I've searched around for this a lot and can't find a specific example of what I'm trying to do. Basically I want to get the value of a textbox, by the name of the text box (not id). Then I want to remove ALL spaces, not just leading or trailing, but spaces in the text too. For example for this html code:

<INPUT style="TEXT-ALIGN: right;" onkeyup="fieldEdit();" onchange="fieldChange();" NAME="10010input" VALUE="4 376,73" readonly >

I have this javascript:

var val = document.CashSheet.elements["10010input"].value; 
val2 = val.replace(<someregex>, '');
alert(val2);

But I've tried many available regex expressions that remove all spaces, but all only seem to remove leading and trailing spaces, for example the value above 4 376,73 should read as 4376,73 in the alert above but it doesn't. After looking into this normal regex for removing spacesfrom a text field contents is not working and I believe its because its being populated in Polish localised settings on the web server. What \u char/regex exp do I need to capture for a "Polish space" so to speak, in ascii it comes up as 20 but the regex exps that most people are suggesting for spaces does not capture it.

like image 465
TMS Avatar asked Oct 18 '10 15:10

TMS


2 Answers

You can use document.getElementsByName to get hold of the element without needing to go through the form, so long as no other element in the page has the same name. To replace all the spaces, just use a regular expression with the global flag set in the element value's replace() method:

var el = document.getElementsByName("10010input")[0];
var val = el.value.replace(/\s/g, "");
alert(val);
like image 192
Tim Down Avatar answered Oct 13 '22 00:10

Tim Down


You need to "generalize" that regexp you're using so it's applied to all matches instead of just the first. Like this:

val = val.replace(/\s/g, '')

Notice the 'g' that modifies the regexp so it becomes "general".

like image 35
Abel Tamayo Avatar answered Oct 13 '22 00:10

Abel Tamayo