2013-10-24 9 views
0

我有一個表單(#waldform),我想只在提交前一個表單(#modelform)後纔出現。 #modelform和#waldform都調用python函數。如果我將#waldform直接包含到html文件中,一切正常,python函數被調用。然而,如果我只在提交#modelform後才顯示,使用jquery,就像我在下面的代碼中一樣,python函數沒有被調用,並且網站的url在最後變成了#。添加了jquery的表單元素沒有執行正確的動作

這裏是jQuery。表單元素被添加到第一個函數中。

$(document).ready(function() { 


    //call estimate python function 
    $(function() { 

     $("#modelform").submit(function() { 

      // post the form values via AJAX... 
      $.post('/estimate', {name: $("#mymodel").val()}, function(data) { 

       var $a_var = data['title'] 
       var $element = $('<div class="item">' + $a_var + '</div><br>'); 

       $('body').append($element) ; 

       //FORM ADDED HERE 
       $('body').append('<form id="waldform" action="#" method="post"><input type="text" id="waldnum" /><input type="submit" value="Wald Test" /></form>'); 


      }); 

     return false ; 
     }); 
    }); 



    //call wald python function 
    $(function() { 

     $("#waldform").submit(function() { 

      //post the form values via AJAX... 
      $.post('/wald', {name: $("#waldnum").val()}, function(data) { 

       var $a_var = data['title'] 
       var $element = $('<div class="item">' + $a_var + '</div><br>'); 

       $('body').append($element) ; 

      }); 

     return false ; 
     }); 
    }); 



}); 

這裏是html,如果需要的話。如果我直接在這個html代碼中包含#waldform,那麼Python函數會被正確調用。

<!DOCTYPE html> 
    <html> 
     <head> 

       <script type="text/javascript" src="static/jquery-1.4.2.js"></script> 
       <script type="text/javascript" src="static/jquery-ui-1.8.4.custom.min.js"></script> 
       <script type='text/javascript' src='static/js_test.js'></script> 
       <script type='text/javascript' src='static/jquery.form.js'></script> 

       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
       <script src="http://malsup.github.com/jquery.form.js"></script> 
     </head> 
     <body> 

      <form id="dataform" action="submit" method="post" enctype="multipart/form-data"> 
       <input type="file" name="myfile" id="myFile"/> 
       <input type="submit" value="Submit File"/> 
      </form> 

      <form id="modelform" action="#" method="post"> 
       <input type="text" id="mymodel" /> 
       <input type="submit" value="Estimate" /> 
      </form> 

     </body> 
    </html> 
+1

$'的兩個實例(函數(){})'在你的代碼是多餘的。 –

+0

謝謝!!!仍在學習jquery:P –

回答

1

在第二個窗體存在之前,您綁定了第二個窗體的提交事件。將其添加後將其移至。

//FORM ADDED HERE 
$('body').append('<form id="waldform" action="#" method="post"><input type="text" id="waldnum" /><input type="submit" value="Wald Test" /></form>'); 

//BIND EVENT HERE 
$("#waldform").submit(function() { 
+0

感謝您快速回復。我不太清楚你的意思。你能更具體一點嗎? –

+1

基本上,當你做'$(「#waldform」)'時,它只會選擇那個時間點存在的元素。未來的因素不會受到它的影響。稍微更新了答案。 –

0

你需要使用。對委派它()

$(document).on('submit', '#waldform', function(e) { 
    alert('clicked'); 
    e.preventDefault(); 
});