2016-02-05 129 views
1

我有一個提交按鈕的HTML表單。我在頭文件中包含一個js函數。我試圖綁定按鈕的onclick事件來調用該函數。但是,我嘗試過的所有方法都不起作用。表單提交按鈕onclick不會調用我的JS功能

<form class="form-horizontal" role="form" id="form_newCours"> 
     <div class="form-group"> 
      <label class="control-label col-sm-2" for="discippline">Matiere:</label> 
      <div class="col-sm-4"> 
       <input type="text" class="form-control" id="discipline" placeholder="Matiere"> 
      </div> 
     </div> 
     <div class="form-group" align="left"> 
      <label class="control-label col-sm-2" for="datetimepicker">Date:</label> 
      <div class="input-group col-sm-4"> 
         <input type="text" class="form-control" id="datetimepicker"/> 
         <span class="input-group-addon"> 
          <span class="glyphicon glyphicon-calendar"></span> 
         </span> 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-sm-offset-2 col-sm-10"> 
       <div class="checkbox"> 
       <label><input type="checkbox" id="creneau_regulier"> Ce creneau regulier</label> 
       </div> 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-sm-offset-2 col-sm-10"> 
       <button type="submit" class="btn btn-default" id="btn-newCours">Ajouter</button> 
      </div> 
     </div> 
</form> 

的JS功能是send_json_req.js:

$.fn.serializeObject = function() 
{ 
var o = {}; 
var a = this.serializeArray(); 
$.each(a, function() { 
    if (o[this.name] !== undefined) { 
     if (!o[this.name].push) { 
      o[this.name] = [o[this.name]]; 
     } 
     o[this.name].push(this.value || ''); 
    } else { 
     o[this.name] = this.value || ''; 
    } 
}); 
return o; 
}; 

$('#form_newCours').on('click',function (e) { 
console.log("Ici"); 
// YK: Bellow is my code 
var jsonString = JSON.stringify($('#form_newCours').serializeObject()); 
console.log($('#form_newCours').serialize()); 
$.ajax({ 
    type: "POST", 
    data : jsonString, 
    url: "/cours/", 
    contentType: "application/json" 
    }); 
}); 

我也試圖直接從上用onclick按鈕調用函數,但沒有奏效。我究竟做錯了什麼 ?

+1

不要使用'type submit'使用'type button' – guradio

+0

你將綁定到表單,嘗試將它綁定到按鈕並將它包裝在[$(document).ready](https://learn.jquery .com /使用jQuery的核心/文件就緒/) –

+0

我沒有看到一個onclick事件被稱爲.. ??在哪裏試圖訪問此功能..? –

回答

1

這些是你的問題:

  1. 包裝你的DOM讀/在$(document).ready(function() { ... });操控代碼 - 這確保了元件可用於操縱。 See guide
  2. 您將click事件綁定到窗體,而不是按鈕。
  3. 您需要在事件處理函數內部使用event.preventDefault();取消表單提交的默認行爲。 See docs.

,這些修改的代碼應工作 - 請花時間去理解書面意見中的變化:

$.fn.serializeObject = function() { 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 
    if (o[this.name] !== undefined) { 
     if (!o[this.name].push) { 
     o[this.name] = [o[this.name]]; 
     } 
     o[this.name].push(this.value || ''); 
    } else { 
     o[this.name] = this.value || ''; 
    } 
    }); 
    return o; 
}; 

// All your code that reads/changes the HTML goes in here: 
$(document).ready(function() { 

    // this was previously bound to the form, not the submit button: 
    $('#btn-newCours').on('click', function(e) { 

    // this will stop the form from submitting normally and let you handle it yourself 
    e.preventDefault(); 

    console.log("Ici"); 
    // YK: Bellow is my code 
    var jsonString = JSON.stringify($('#form_newCours').serializeObject()); 
    console.log($('#form_newCours').serialize()); 
    $.ajax({ 
     type: "POST", 
     data: jsonString, 
     url: "/cours/", 
     contentType: "application/json" 
    }); 
    }); 

}); 

有一個fiddle here。它不會執行任何操作,但是當您單擊該按鈕時,瀏覽器的控制檯將顯示禁止的請求,表明正在嘗試發送數據。

+0

謝謝喬希哈里森。您的更改使其工作。雖然我仍然不明白爲什麼我們不能修改html元素,如果沒有把代碼放在document.ready中? – Spider

+1

從技術上講,你不必使用'$(document).ready()' - 如果你的JavaScript被包括在你正在使用的HTML元素之後,你不必這樣做,因爲在瀏覽器到達JavaScript將已經「看到」相關的HTML。但是,如果您的JavaScript在相關的HTML之前出現,它將馬上運行該腳本,並且瀏覽器將不會「看到」該HTML,這將導致錯誤。使用jQuery的'$(document).ready()'意味着你可以把你的javascript放在任何地方,而不用擔心這一點。希望有助於 –

+0

[這個答案](http://stackoverflow.com/a/13062316/940252)也可能有助於解釋它。 –

1

$('#form_newCours').on('submit', function(){}) 
 
//use submit action on form element then callback will trigger

0

您可以將您的按鈕選擇點擊

$('#btn-newCours').on('click',function (e) 

或設置形式選擇提交(這是更好)的其他答案建議

1

更改爲:

$('#form_newCours').on('submit',function (e) { 
    e.preventDefault(); // prevents the form from submitting as it normally would 

    ... 
} 
1

使用anchor標記或button與類型,但如果您使用type="submit"確保在函數調用的開始event.preventDefault()

<a href="" onclick="someFunction()">Submit</a> 
    <button type="button" onclick="someFunction()"></button> 
    <button type="submit" onclick="someFunction()"></button> /* in this case include function someFunction(event){ event.preventDefault(); ...} */ 

還有一件事,如果你使用一個單獨的文件,確保它被加載。因此,更好的解決方案將在HTML頁面中包含submit函數。

希望這會有所幫助。

+0

這在我看來是最好的答案。從HTML文檔的角度來看,'type =「button」'表示清楚。不需要額外的JS操作。 – sargas