简体   繁体   中英

How to post to a form using <a> tag and passing hidden value?

If I had some coding as follow.

<form method="POST" action="localhost/carts/delete">
  <a href="#" onclick="$(this).closest('form').submit();">Item 1</a>
  <a href="#" onclick="$(this).closest('form').submit();">Item 2</a>
  <a href="#" onclick="$(this).closest('form').submit();">Item 3</a>
</form>

And I like to post to a form with some hidden value to indicate which Item is clicked, how to do that???

Thanks.

Edited Text.

Thanks for so many useful suggestions.

I actually use Laravel 4 rather than PHP, my Laravel code produced this HTML

<form ...>
  <ul>
    <li> 
      <h1>Key: 1 </h1>
      <input name="cart_id" type="hidden" value="1"><a href="#" onclick="$(this).closest('form').submit()">Delete</a>
    </li>
    <li> 
      <h1>Key: 2 </h1>
      <input name="cart_id" type="hidden" value="2"><a href="#" onclick="$(this).closest('form').submit()">Delete</a>
    </li>
    <li> 
      <h1>Key: 6 </h1>
      <input name="cart_id" type="hidden" value="6"><a href="#" onclick="$(this).closest('form').submit()">Delete</a>
    </li>
    <li> 
      <h1>Key: 7 </h1>
      <input name="cart_id" type="hidden" value="7"><a href="#" onclick="$(this).closest('form').submit()">Delete</a>
    </li>
  </ul>
</form>

So, when I clicked on any items, I got 7 which is the last value of cart_id, how to place at the right place, in JavaScript???

Create a hidden element inside the form:

<form method="POST" action="localhost/carts/delete">
    <input type="hidden" name="myValue" value="" id="myValue"/>

    <a href="#" data-value="1">Item 1</a>
    <a href="#" data-value="2">Item 2</a>
    <a href="#" data-value="3">Item 3</a>
</form>

Then on click over any link ( a ) change its value and submit the form.

$('a').click(function(e){
    //preventing the default link redirection
    e.preventDefault();

    $('#myValue').val($(this).data('value'));
    $(this).closest('form').submit();
});

Use a hidden input field like:

<input type="hidden" value="hidden value" name="id"/>

This box is not visible in your page.

Use input fields instead.

<form method="POST" action="localhost/carts/delete">
  <input type="submit" value="Item 1" name="whichitem[]" />
  <input type="submit" value="Item 2" name="whichitem[]" />
  <input type="submit" value="Item 2" name="whichitem[]" />
</form>

Then in PHP you can retrieve the clicked value like this:

$_POST["whichitem"]

If you are worried about the styling, simply add it in your css:

input[type="submit"]{
   //style
}

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