Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with FOR Loop

Status
Not open for further replies.

milo3169

Programmer
May 2, 2007
42
Hi All,

I have this function where you can select multiple selections from a Listbox and it will copy those selections into a text area box.
Code:
function duplicateValue()
{
var main = document.getElementById('main');
var duplicate = document.getElementById('duplicate');
		
	for(var i = 0; i < main.options.length; i++)
	{
		if(main.options[i].selected)
		{				
			var item = main.options[i].value;
			main.options[i] = null;
			duplicate.value += item + "\n";

				
		}

	}
}

What I want to do if this is possible is to be able to automatically remove the last "\n" from the text area list before I submit the form. Is there a way I can do that? If so, how? I've been going nuts trying to figure this out. Anyone’s help would be appreciated.
 
You're making multiple changes to the value of the HTML element. This can be a costly process in a big loop. Instead, build the output into a string, and at the end of the procedure throw the string to the HTML element value. Additionally, you can easily take off the trailing \n before you put the value into the HTML element:
Code:
function duplicateValue() {
    var main = document.getElementById('main');
    var duplicate = document.getElementById('duplicate');
    var str = "";
        
    for(var i = 0; i < main.options.length; i++) {
        if(main.options[i].selected) {                
            main.options[i] = null;
            str += main.options[i].value + "\n";
        }
    }
    duplicate.value = str.replace(/\n$/, "");
}

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Oh, OK. I tried what you wrote and it works. Thanks a lot Kaht.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top