What is the simplest way to retain the last option value selected in an
html select object using javascript?
What do you mean by 'retain'? Do you mean to have it selected on the
following page?
I am currently using a server-side cgi language to accomplish this
task, but it adds a lot of overhead and I would like to move the
overhead to the remote client's PC, using javascript.
You can't depend on JavaScript being available on the client, so if this
is important, continue the server-side support. However, you might be
able to design your page so that if javascript is available and has
support for suitable features, you can perhaps skip a trip to the server.
The selected option of a select element is given by the selectedIndex
property. Below is a trivial demo:
<script type="text/javascript">
function showSelected(sel)
{
if (sel && document.getElementById){
var msg = '';
var selIndex = sel.selectedIndex;
var selOption = sel.options[selIndex];
msg += 'Selected index: ' + selIndex
+ '<br>Value: ' + selOption.value
+ '<br>Text: ' + selOption.text;
document.getElementById('xx').innerHTML = msg;
}
}
</script>
<select onchange="showSelected(this);">
<option value="opt0">Option 0</option>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
<option value="opt3">Option 3</option>
</select>
<br>
<span id="xx"></span>
If your question is how to have the same option selected on the
following page the best place to do that is on the server by setting the
appropriate option to 'selected' in the HTML. Then if the form is
reset, the correct option is still selected. If client-side script is
used to select the option, you have to accommodate reset and reloads, as
well as the back button.
Unless you can provide more detail, I think you should stick to your
current server solution.
[...]