2013-12-21 145 views
0

之間的任何區別我試圖用一個隱藏的值(這是一個循環的當前迭代)向我的web服務器提交表單。<input type =「submit」> button和javascripts .submit()

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

當我使用提交按鈕,一切工作正常。我試圖通過點擊包含字符串的div來模擬這種行爲,我希望用戶能夠點擊該字符串。

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

這onclick事件總是發送形式與上一次迭代ID(如果有我的網頁上五行中,entry.id將始終被作爲5個)。

任何我可以通過使用div單擊事件或某種不涉及按鈕的jQuery事件模擬提交按鈕的行爲的方式都會很棒。我正在使用Jinja 2模板(Flask Framework)。謝謝!

+1

http://jsfiddle.net/FSvYL/5/在這兩個點擊,將重新加載頁面 –

+0

是的,頁面在這兩種情況下重新加載。我的問題在於表單中的值以及它們在提交表單的兩種方法之間的差異。感謝您在jsfiddle上託管。 – n0dnarb

+0

發佈的代碼不會重現該問題。您需要提供更多信息。你有沒有使用相同的'ID'多種形式? –

回答

-1
<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> 
+0

這不是一個答案。問題中的代碼使用'id'屬性來引用表單,這與一些間接的基於jQuery的方式一樣好(或優於)。 –

0

我有一個循環要通過「條目」在主頁上發佈。

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

我改變了表單ID以將當前循環的迭代附加到每個表單的ID。

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

下面是更正後的來源,包括具有單擊事件的div。

{% 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 %}} 
相關問題