我有一個提交按鈕的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按鈕調用函數,但沒有奏效。我究竟做錯了什麼 ?
不要使用'type submit'使用'type button' – guradio
你將綁定到表單,嘗試將它綁定到按鈕並將它包裝在[$(document).ready](https://learn.jquery .com /使用jQuery的核心/文件就緒/) –
我沒有看到一個onclick事件被稱爲.. ??在哪裏試圖訪問此功能..? –