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.

+2


source to share


4 answers


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>

      

+2


source


You add the selected attribute with any (for example empty) value to the one you want to keep selected.



+2


source


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>";
}
0


source


You can pass the hidden form variable to the next posted page. Using a simple Javascript function that scans through the options of the dropdown select, if any of the options matches a hidden value, set its selected

sttribute.

0


source







All Articles