How to keep the dropdown state constant?
I am making a simple web application that has a dropdown on the first page in form tags. Now the wen changes the value in the dropdown list of the form. On onchange
I made a call to create a custom JS function to query the selected index. Now I want the dropdown to keep its state; keep the last selected value after sending.
Friends, how can I do this?
Thanks everyone.
source to share
The getQueryValue function is a bit unoptimized and would probably do better with a regex to get the value, but I just typed it so you can see what it does.
<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>
source to share
Depending on how your page will be handled after submission, if it goes to PHP / Perl or some other language to rebuild the page, then put the dropdown options in your script and swipe through them.
Something like this is a fairly common place
for ($ i = 0; $ i <10; $ i ++) { echo "<option value = '{$ i}'"; ($ i == $ _POST ['dropdownname'])? echo "selected = 'selected'": ""; echo "> {$ i} </option>"; }
source to share