简体   繁体   中英

Any difference between an <input type=“submit”> button and and javascripts .submit()

I am trying to submit a form to my web server with a hidden value (which is the current iteration of a loop).

<form id="question_id_to_delete" action = "{{url_for('delete_question')}}" method="post">
          <input type="hidden" name=id value={{entry.id}}>
          <input type="submit">
</form>

When I use the submit button, everything works correctly. I'm trying to emulate this behavior by clicking on the div containing the string I'd like the user to be able to click on.

<div id="question" onclick="document.getElementById('question_id_to_delete').submit()"> {{entry.question}} </div>

This onclick event always sends the form with with the last iteration ID (if there are five elements on my page, the entry.id will always be sent as five).

Any way that I could emulate the behavior of the submit button by using a div click event, or some sort of jQuery event not involving a button, would be great. I'm using Jinja 2 templating (Flask Framework). Thank you!

I had a loop going through "entries" to post on the main page.

 {% for entry in entries %}
      <form id="delete_question" ...>
 {% endfor %}

I changed the form ID to append the current iteration of the loop to each form's ID.

<form id="delete_question_{{entry.id}}" ...>

Here's the source of after the correction, including the div that has the click event.

{% for entry in entries %}
      <form id="delete_question_{{entry.id}}" action ="{{url_for('delete_question')}}" method="post">
          <input type="hidden" name="id_to_delete" value={{entry.id}}>
      </form>
      <div id="question" onclick=document.getElementById("delete_question_{{entry.id}}").submit() >
          <li><h2>{{entry.question}}</h2>
      </div> {% endfor %}}
<form id="question_id_to_delete" action="{{url_for('delete_question')}}" method="post">
  <input type="hidden" name=id value={{entry.id}}>
  <div class="special-submit-button"></div>
</form>

<script>
  // include jQuery before this script tag
  $('.special-submit-button').on('click', function(e) {
    // DIV button livs inside the form. so find the form and submit it
    // doing it this way, makes this code more universal. you can now port this 
    // to OTHER FORMS that use the same idea, without having to change it
    // simply by applying the special-submit-button class to the submitter div.
    // this IS an answer.
    $(this).closest('form').submit();
  });
</script>

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