How to change input type hidden value when select option changed

Advertisements

I am trying to change input type hidden value when select option submit.

if the select box option choose, the list line count changed. but the problem is if I click the page number 2 then select option value, the page number still stay at number 2. I wnat to change page number to 1 when i selected option.

the page number value is input type hidden value (nowPage)

this tis the select box and input

<form action="/list.do" name="searchForm" id="searchForm" method="get">
<input type="hidden" id="nowPage" name="nowPage" value="<%=request.getParameter("nowPage")%>">
<select name="boardlineCount" id="boardlineCount" title="count" onchange="this.form.submit();">
  <option value="10">count</option>
  <option value="5" <c:if test="${param.boardlineCount eq '5'}">selected </c:if>>5</option>
  <option value="30" <c:if test="${param.boardlineCount eq '30'}">selected </c:if>>30</option>
  <option value="50" <c:if test="${param.boardlineCount eq '50'}"> selected </c:if>>50</option>
  <option value="100" <c:if test="${param.boardlineCount eq '100'}"> selected </c:if>>100</option>
</select>
</form>

this is the script that is tried. am I miss somthing?

<script>
  $(function(){
        $('#boardlineCount').on('change',function(){
            $("#nowPage").val("1");
        console.log("?????");
        });
    });
</script>

>Solution :

The problem is that you’re automatically submitting the form when your <select> value changes due to onchange="this.form.submit();".

Attribute event handlers like onchange execute before added event listeners.

document.querySelector("select").addEventListener("change", (e) => {
  console.log("change event listener fired:", e.target.value);
});
<select onchange="console.log('onchange attribute fired:', this.value)">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

Remove the onchange attribute and instead, perform the form submit in the change event listener that also sets your #nowPage element.

document.getElementById("boardlineCount").addEventListener("change", (e) => {
  document.getElementById("nowPage").value = 1;
  e.target.form.submit();
});

FYI, there’s no need for jQuery but if you insist…

$("#boardlineCount").on("change", (e) => {
  $("#nowPage").val(1);
  e.target.form.submit();
});

Leave a ReplyCancel reply