简体   繁体   中英

Submit form from a link with param


I'm trying and searching now for days and can't find an answer.
My problem is this: I use a Hyperlink and Javascript to submit a form, but I also need to submit a parameter with the link. The code looks like this:

<form action="Action.jsp" method="post" id="form-id">
  <input .../>
  ...
  <c:forEach items="${items}" var="item" varStatus="vs">
    <a href="Action.jsp?id=${vs.count}" 
       onclick="javascript:document.forms['form-id'].submit(); return false">
       ${vs.count}
    </a>
  </c:forEach>
</form>

If I leave away the return false the param id is transferred but the other <input .../> parameters not and vice versa. How you see I can't use a <input type="hidden" .../> param, because I need only the param of the link.

If you please could help me, I would be grateful....

You need to add your parameter into the action property of form as well. This determines what URL the page is submitted to when submit occurs.

So you will probably need to use javascript to change this property value when the link is clicked to where it behaves like this.

<form action="Action.jsp?id=${vs.count}" method="post" id="form-id">

When you remove return false , what you are in essence doing is just getting the default behavior of the link after the form quickly submits.

If you add a hidden input outside the loop, you can set the value of that input before submitting:

<form action="Action.jsp" methode="post" id="form-id">
  <input .../>
  <input type="hidden" id="button-id"/>
  ...
  <c:forEach items="${items}" var="item" varStatus="vs">
    <a href="Action.jsp" 
       onclick="javascript:document.getElementById('button-id').value=${vs.count};document.forms['form-id'].submit(); return false">
       ${vs.count}
    </a>
  </c:forEach>
</form>

If you don't need to have anchors, you could solve this without JavaScript by submitting using button elements instead:

<button name="id" type="submit" value="${vs.count}">${vs.count}</button>

Note that Internet Explorer, prior version 8, will submit the text between the <button> and </button> tags, while other browsers will submit the value.

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