单击表单提交按钮不会调用我的 JS 函数

Form submit button onclick does not call my JS function

本文关键字:我的 JS 函数 调用 表单提交 按钮 单击      更新时间:2023-09-26

我有一个带有提交按钮的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 直接从按钮调用该函数,但它不起作用。我做错了什么?

这些是你的问题:

  1. 将 DOM 读取/操作代码包装在 $(document).ready(function() { ... }); 中 - 这可确保元素可用于操作。请参阅指南。
  2. 您正在将单击事件绑定到窗体,而不是按钮。
  3. 您需要使用事件处理程序中的event.preventDefault();取消表单提交的默认行为。请参阅文档。

这个编辑过的代码应该可以工作 - 请花时间理解注释中写的更改:

$.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"
    });
  });
});

这里有一个小提琴。它不会执行任何操作,但当您单击该按钮时,浏览器的控制台将显示禁止的请求,表明正在尝试发送数据。

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

更改为:

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

使用带有 type 的 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 页面本身中包含提交功能。

希望这有帮助。

您可以在单击按钮时设置选择器

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

或在表单提交时设置选择器(哪个更好),如其他答案建议的那样