我有一个带有提交按钮的 html 表单。我在头部包含的文件中有一个 js 函数。我试图绑定(bind)按钮的 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 直接从按钮调用函数,但没有成功。我究竟做错了什么 ?
最佳答案
这些是您的问题:
- 将您的 DOM 读取/操作代码包装在
$(document).ready(function() { ... });
- 这确保元素可用于操作。 See guide . - 您将点击事件绑定(bind)到表单,而不是按钮。
- 您需要在事件处理程序中使用
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 .它不会执行任何操作,但当您单击该按钮时,浏览器的控制台会显示禁止请求,表明正在尝试发送数据。
关于javascript - 表单提交按钮 onclick 不调用我的 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35221978/