Jump to content

Looping Through Form To Replace Values


xjx424
 Share

Recommended Posts

Hi, I am trying to use "replace" to remove dollar signs and commas from input values by looping through the elements. I'm pretty sure I have to use an array in an array to do so but can't figure it out.Here's what I have:

function removeStuff(){	for(j=0; j<document.form1.elements.length; j++) {	remove = new Array("$", ",");		for(i=0; i<remove.length; i++) {			newValue = document.form1.elements[j].value.replace(remove[i],"");		}	}alert(newValue);}

Any ideas what I'm doing wrong?Thanks!

Link to comment
Share on other sites

You're not doing anything with newValue after you do the replacement. You should assign it back to the form element. Also, you should move the definition of the remove array out of the loop, there's no reason to redefine it every time through the loop.

Link to comment
Share on other sites

you're working too hard, the replace method can take a regular expression as its input, try this

<script language="javascript" >function removeStuff(){	var oElements =  document.getElementById("form1").elements	for (j=0; j < oElements.length; j++)	{		oElements[j].value = oElements[j].value.replace(/[$,]/g,'')	}}</script><form id="form1">	<input type="text" name="text1" />	<input type="text" name="text2" />	<button onClick="removeStuff()">RemoveStuff</button></form>

Link to comment
Share on other sites

that's pretty much what I came up with. Just changed

for(j=0; j<document.form1.elements.length; j++) {	remove = new Array("$", ",");		for(i=0; i<remove.length; i++) {			newValue = document.form1.elements[j].value.replace(remove[i],"");		}	}

to

remove = new RegExp("[\$,]","g");	for(j=0;j<document.form1.elements.length;; j++) {		newValue = document.form1.elements[j].value.replace(remove,"");			}

Thanks

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...