Click to See Complete Forum and Search --> : How to show a "selected" value in a select box?


weee
04-23-2007, 12:07 PM
I have a "edit info" page and I got a select box with a few options and I'd like to show the user his selection (a value from a db) in the select box.

I tried something like that, but it doesn't work:
onload=function() {
document.formName.fieldName.options[document.formName.fieldName.selectedIndex].value = '<%=fieldValue%>'
}

Maybe other techniques?

gil davis
04-23-2007, 12:48 PM
Look at http://www.webdeveloper.com/forum/showthread.php?t=140767. It contains a technique for setting the selected attribute for a dropdown when you build the dropdown.

weee
04-23-2007, 01:04 PM
Well the thing is that I'm NOT using a database for the different options in the select box.

Do you think that JavaScript is not a good solution?

gil davis
04-23-2007, 01:33 PM
What you posted contained ASP, and this is an ASP forum. Perhaps I assumed incorrectly that you were after an ASP solution?

For it to work in JavaScript, you would have to test the value of each object in the dropdown for a match to "fieldValue" assuming it is a string. The one at "selectedIndex" would be what the user has currently selected. Something like this:
window.onload = function() {
var sel = document.formName.fieldName;
var it = -1;
for (var i=0; i<sel.options.length; i++)
{if (sel.options[i].value == "<%=fieldValue%>")
{it = i;}
}
if (it >= 0)
{sel.selectedIndex = it;}
}

orionbrock32
04-23-2007, 01:42 PM
it may be more cumbersome but i always just do if statements for each option using the info from the db such as:



<td height="28">
Carrier<input type="radio" name="Container" value="Carrier"
<%Container2=currentRecord(17)
IF Container2= "Carrier" THEN%>checked<%END IF%>>&nbsp;

Shipper
<input type="radio" name="Container" value="Shipper"
<%IF Container2= "Shipper" THEN%> checked<%END IF%>>

</td>