PDA

View Full Version : Select box value


ghornet
03-28-2003, 06:21 PM
I have 'borrowed' the following code (: But it is doing something that I don't know how to fix, basically all I am trying to do is alert up the different options that somebody has choosen from a select box, but when I run the following code nothing happens the first time, but the next time I click on something it gives me the value from the first time I clicked, or also the line that is commented out //alert(opt.length); if I uncomment that it works just fine. I am sure that it is a problem with a variable not being set right... anyone have any ideas?

function getSelected(opt) {
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].selected)
{

index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}

function class_onclick()
{

opt = document.all['SelectClass'].options;
//alert(opt.length);
var sel = getSelected(opt);
var strSel = "";
for (var item in sel)
strSel += sel[item].value + "\n";
alert("Selected Items:\n" + strSel);


}

HairyTeeth
03-28-2003, 06:57 PM
... something like this you mean?


<html
<head>
<title>Select Test</title>

<script language="javascript" type="text/javascript">
<!--
function getSelection(form){
var result=""
for(var i=0; i<form.selList.length;i++){
if(form.selList.options[i].selected){
result += "\n - " + form.selList.options[i].value
}
}
alert("You have selected " + result)
}
//-->
</script>
</head>
<body>

<h3>Single Select</h3>

<form>
<select name="selList">
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="White">White</option>
</select>
<input type="button" value="Get Selection" onclick="getSelection(this.form)" />
</form>

<h3>Multi-Select<h3>

<form>
<select name="selList" size="5" multiple="multiple">
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="White">White</option>
</select>
<input type="button" value="Get Selection" onclick="getSelection(this.form)" />
</form>

</body>
</html>

ghornet
03-28-2003, 07:14 PM
Yes except I want it on click of the select box

D--

ghornet
03-28-2003, 07:23 PM
function class_onclick(form){
{
var result=""

for(var i=0; i<document.all['SelectClass'].length;i++){
if(document.all['SelectClass'].options[i].selected){
result += "\n - " + document.all['SelectClass'].options[i].value

}
}
alert("You have selected " + result);

}

Thanks

D--