【发布时间】:2016-02-05 22:29:05
【问题描述】:
我有一个带有提交按钮的 html 表单。我在头部包含的文件中有一个 js 函数。我正在尝试绑定按钮的 onclick 事件来调用该函数。但是,我尝试的所有方法都不起作用。
<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 -
您正在将偶数绑定到表单,尝试将其绑定到按钮并将其包裹在$(document).ready
-
我没有看到 onclick 事件被调用..??在哪里尝试访问此功能..?
标签: javascript jquery html