简体   繁体   中英

Recall selected value of a dropdown

I am attempting to recall a selected value of a drop down box after my servlet has ran the query on my database.

There is no limit on variables so i have used c:foreach to populate the drop-down.

The code is as follows

 function moduleLookup() { var trainId = document.getElementById("Selector").value; document.trainForm.trainId.value = trainId; document.trainForm.submit(); } 
 <select id="Selector" onchange="moduleLookup()" onchange=storeValues()> <option value="/javaTrainingServletProject/UserAdministration?id=0">Select module</option> <option value="0">All Modules</option> <c:forEach items="${modules}" var="module"> <option value="${module.id}">${module.title }</option> </c:forEach> </select> 

I have tried every method I can find to get the refreshed drop down to have the previously selected value. I have tried to add cookie data but, I am new to jquery.

In the listener, you can pass a reference to the element using this :

<select id="Selector" onchange="moduleLookup(this)" ...>

Then in the function you can do:

function moduleLookup(select) {
  var trainId = select.value;
  ...
}

Note also that to be successful (and hence be submitted with the form), a form control must have a name. The select element only has an id (which should be redundant now, so make it a name).

If you want to restore the selected value, you can store the selectedIndex and restore that later. If you are submitting the form, the page will refresh so perhaps you can just set the appropriate option's selected attribute when generating the HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM