AN************************@yahoo.com wrote:
Rob,
Thank you for your reply. By "retain," I do mean to have the last
option value selected on the following page. I realize that some users
will not have javascript enabled, but I am willing to risk this for the
sake of drastically decreasing the load time of the page. The select
object in question has about 1000 option, value pairs and preforming
the selected function server-side is taxing.
What would the javascript code for preforming the selected function
client-side look like?
Presumably the page is posting to itself. You could store data in a
cookie, but that is unreliable. Location.search may be better.
In the script below, a global object called 'KeepSet' has the names of
select elements that are to be kept set. The script looks through all
the control names in the search string and if a matching name is in
KeepSet, it uses the value to set the selected index. The index of the
option is appended to the value - if the value ends in a number,
separate the index by some non-digit character. You could add the
values on the server and trim them when you get them back.
Alternatively, pre-pend the index.
There are many variations on the theme, this probably won't suit but you
may want something like it. An alternative is to search through the
select's options to find a matching value and then set that as selected.
If you have lots of options, that may take some time...
<script type="text/javascript">
// Put the elements to be reset in here
var KeepSet = {
'sel-01':true,
'sel-02':true
};
function setOption()
{
// Get the search string
var searchString = location.search.substring(1);
var a, b, idx;
// If there is a search string
if (searchString.length) {
// Get the components
var a = searchString.split('&');
// For each component
for (var i=0, len=a.length; i<len; ++i){
// Get the control name and value
b = a[i].split('=');
// If a matching name is found in KeepSet
if (KeepSet[b[0]]){
// Get the index (trailing digits) from the value
idx = b[1].match(/\d+$/)[0];
// Set the select's selectedIndex to that value
document.forms['form-01'].elements[b[0]].selectedIndex = idx;
}
}
}
}
window.onload = setOption;
</script>
<form action="" name="form-01">
<select name="sel-01">
<option value="opt0">option 1-1</option>
<option value="opt1">option 1-2</option>
<option value="opt2">option 1-3</option>
</select>
<select name="sel-02">
<option value="opt 0">option 2-1</option>
<option value="some value 1">option 2-2</option>
<option value="3 value 67 2">option 2-3</option>
</select>
<select name="sel-03">
<option value="opt 0">option 3-1</option>
<option value="opt 1">option 3-2</option>
<option value="opt 2">option 3-3</option>
</select>
<input type="submit">
</form>
[...]
--
Rob