Hi,

I created a multiple select box wich i would like to have one variable with all the results selected on the multiple select box such as variable_name = "result1|result2|result3"

This is what i have so far:

oSelect = document.getElementById ('s1');
var iNumSelected = 0;

   for (var iCount=0; oSelect.options[iCount]; iCount++) {
        if (oSelect.options[iCount].selected == true) {
            iNumSelected ++;
            alert(oSelect[iCount].value); // this part alerts all the result within the loop
        }
   }

Now what i exactly need is to have a variable called "test" outside of the loop wich i have all the selected results separated with an "|", so that when i do alert(test) displays all results as a one result.

Hope someone can help

Thanks

Declare a variable 'test' outside the loop and inside the loop append the value of the selected option along with a '|' to `test'. Try it. Did you get the desired result? If no, then why? What seems to be missing here? What do you think needs to be done to make it work the way you expect?

Hi, thanks for the reply but that's my problem on how to append everything on the variable , on php i usually do $test .= $array_var."|"; and outside the loop i just do echo $test, now how's that done in javascript?

Thanks

oSelect = document.getElementById ('s1');
var iNumSelected = 0;
var str="";
   for (var iCount=0; oSelect.options[iCount]; iCount++) {
        if (oSelect.options[iCount].selected == true) {
            iNumSelected ++;
            str+= "|" + oSelect.options[iCount].value
        }
   }
alert(str);

Hi mohammed thanks for your answer, i tried that but it says object expetcted when i run the script. if i remove str+= to str= it works but it doesn't show all results.

Any alternatives?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<script>
function show()
{
	var ss= document.getElementById('s1');
	var len= ss.options.length;
	var str="";
	var j=0;
	for(var i=0;i<len;i++){		
		if(ss.options[i].selected == true)
		{			
		if(j == 0)
			str= ss.options[i].innerHTML;
		else
			str += '|' + ss.options[i].innerHTML;
		j++;
		}
	}
	alert(str);
}
</script>

</HEAD>

<BODY>
	<select id="s1" size=3 multiple>
		<option> Raja1 </option>
		<option> Raja2 </option>
		<option> Raja3 </option>
		<option> Raja4 </option>
		<option> Raja5 </option>
	</select>
	<div>
	<input type="button" onclick="show();">
	</div>
</BODY>
</HTML>

I think this can help u.

thanks mohammed2raja it works perfectly many thanks!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.