tarashypka tarashypka - 4 months ago 28
Javascript Question

retain HTML select option in jsp dilemma

I have a form with select input, and I want to retain the selected option after submit.

So far I have found 2 solutions:

select1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Select 1</title>
<script>
function submitSelected1() {
document.form1.selected.value = document.form1.item.selectedIndex;
document.form1.submit();
}
function retainSelected1(selected) {
if (selected) document.form1.item.selectedIndex = selected;
}
</script>
</head>
<body onload="retainSelected1(${param.selected})">
<form name="form1" action="${pageContext.request.contextPath}/controller" method="post">
<select name="item" onchange="submitSelected1()">
<option selected disabled>-- select item --</option>
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4">Item4</option>
</select>
<input type="hidden" name="selected" value="">
<button type="submit">Submit</button>
</form>
</body>
</html>


select2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Select 2</title>
<script>
function retainSelected2(selected) {
document.querySelectorAll('[name=form2] option[value="' + selected + '"]')[0].defaultSelected = true;
}
</script>
</head>
<body onload="retainSelected2(${param.item})">
<form name="form2" action="${pageContext.request.contextPath}/controller" method="post">
<select name="item">
<option selected disabled>-- select item --</option>
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4">Item4</option>
</select>
<button type="submit">Submit</button>
</form>
</body>
</html>


The question is in which one is better and why. I am also interested in if there are any better solutions to accomplish this.

Answer

Use sessionStorage to retain your values & have something stateful :

On Submit :

  • Save selected option value just before submit.

       sessionStorage.setItem('LAST_SELECTED',document.querySelectorAll('[name=form1] option[selected]')[0].value);    
    

    ;

On Page Load :

  • Get the value of last selected option :

     var value=sessionStorage.getItem('LAST_SELECTED');
    

    _ Set Selected Option :

    document.querySelectorAll('[name=form1] option[value="'+value+'"]')[0].defaultSelected = true