0

Hi,

I have a function in java script like this.I want to append a comma in reason_txts only if there is second element in array

function(result_arr){
            var reason_ids="",reason_txts="";
            for(i=0;i<result_arr.length;i++){
                reason_ids+=result_arr[i].id+",";
                reason_txts+=result_arr[i].col0+",";
            }
            document.getElementById("reasonIds_disp_hdn").value= reason_ids;
            document.getElementById("appReason_text").value= reason_txts;
            document.ViewSlot.appReason_text.className="txtbox2";
        }

I tried like this,

function(result_arr){
            var reason_ids="",reason_txts="";
            for(i=1;i<=result_arr.length;i++){
                reason_ids+=result_arr[i].id+",";
                if(i == result_arr.length)
                    reason_txts+=result_arr[i].col0;
                else
                    reason_txts+=result_arr[i].col0+",";
            }
            alert(reason_txts);
            document.getElementById("reasonIds_disp_hdn").value= reason_ids;
            document.getElementById("appReason_text").value= reason_txts;
            document.ViewSlot.appReason_text.className="txtbox2";
        }

but this alert itself not coming ---> alert(reason_txts);

Eg: if the input is a and b i want a,b in reason_txts

 if the input ia a 
 i want a alone in reason_txts without any comma appended.

suggest me...

Edited by mike_2000_17: Fixed formatting

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by anandhikrishnan
0

Anandhikrishnan,

+= is very inefficient when used to aggregate a string from many component strings. Never ever do it this way.

Instead, aggregate the component strings in an array then use array.join(glue) to put the pieces together. By default the "glue" is ',' (comma).

function(result_arr) {
	var reason_ids = [];//equivalent to new Array()
	var reason_txts = [];//equivalent to new Array()
	for(i=1; i<=result_arr.length; i++) {
		reason_ids.push(result_arr[i].id);
		reason_txts.push(result_arr[i].col0);
	}
	document.getElementById("reasonIds_disp_hdn").value= reason_ids.join();
	document.getElementById("appReason_text").value= reason_txts.join();
	document.ViewSlot.appReason_text.className="txtbox2";
}

If you want a trailing comma on reason_ids, then use reason_ids.join() + ','; .
Airshow

0

Thanks Lucky.

I'm so glad there's somebody out there checking my work. You could have a job for life. I regret to say the wages are very poor.

Line 4 should read

for(i=1; i<result_arr.length; i++) {

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.