Skip to content
Advertisement

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement