我有一个带有选择输入的表单,我希望在提交后保留所选的选项。
到目前为止,我找到了2个解决方案:
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>
问题在于哪个更好,为什么。如果有更好的解决方案可以实现这一点,我也很感兴趣。
答案 0 :(得分:1)
使用sessionStorage
来保留您的价值观&amp;有一些有条不紊的东西:
在提交之前保存所选的选项值。
sessionStorage.setItem('LAST_SELECTED',document.querySelectorAll('[name=form1] option[selected]')[0].value);
获取上次选择的选项的值:
var value=sessionStorage.getItem('LAST_SELECTED');
_设置选定选项:
document.querySelectorAll('[name=form1] option[value="'+value+'"]')[0].defaultSelected = true