Hi All,
I am making a simple web app that has drop down list in the first page in a form tags.
Now wen I change the value in the dropdown the form is submitted. On the onchange
I have made call to create a query string custom JS function of the selected Index.
Now I want the drop down list to maintain its state; keep the last selected value selected after submission.
Friends how can I do this?
Thank You All.
views:
474answers:
4You add the selected attribute with any (e.g. blank) value to the you want to keep selected.
Depends on how your page is dealt with after submission, if it goes to a PHP/Perl or whatever language to rebuild the page, then put the drop down options into a script and loop through them.
Something like this is pretty common place
for($i = 0; $i < 10; $i++){ echo "<option value='{$i}' "; ($i == $_POST['dropdownname'])? echo "selected='selected'":""; echo ">{$i}</option>"; }
You could pass a hidden form variable to the next posted page. Using a simple Javascript function that loops through the options of the selection drop-down list, if any of the options match the hidden value, then set its selected
sttribute.
The getQueryValue function is a bit unoptimized and would probably be better accomplished with a regular expression match to get the value, but I just typed it out like this so you could see what it was doing.
<html>
<head>
<script type="text/javascript">
function setSelections()
{
document.myForm.mySelect.value = getQueryValue("mySelect");
};
function getQueryValue(key)
{
var queryString = window.location.search.substring(1);
var queryParams = queryString.split("&");
for(var i = 0; i < queryParams.length; i++)
{
if(queryParams[i].indexOf("=") > 0)
{
var keyValue = queryParams[i].split("=");
if(keyValue[0] == key)
{
return keyValue[1];
}
}
}
return null;
}
</script>
</head>
<body onload="setSelections();">
<form name="myForm" action="" method="get">
<select id="mySelect" name="mySelect" onchange="document.myForm.submit();">
<option value="Opt1">Option 1</option>
<option value="Opt2">Option 2</option>
<option value="Opt3">Option 3</option>
<option value="Opt4">Option 4</option>
</select>
</form>
</body>
</html>