在jsp困境中保留HTML选择选项

时间:2016-07-30 00:22:56

标签: javascript html jsp html-select

我有一个带有选择输入的表单,我希望在提交后保留所选的选项。

到目前为止,我找到了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>

问题在于哪个更好,为什么。如果有更好的解决方案可以实现这一点,我也很感兴趣。

1 个答案:

答案 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