Jump to content

Looping Through Form To Replace Values


xjx424

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...