我有一个提交按钮的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事件被称为.. ??在哪里试图访问此功能..? –