【问题标题】:Form submit button onclick does not call my JS function表单提交按钮 onclick 不调用我的 JS 函数
【发布时间】: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


【解决方案1】:

这些是你的问题:

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

这个编辑过的代码应该可以工作 - 请花点时间了解用 cmets 编写的更改:

$.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。它不会做任何事情,但是当您单击该按钮时,您的浏览器控制台会显示一个禁止的请求,表明正在尝试发送数据。

【讨论】:

  • 谢谢乔什·哈里森。您的更改使其工作。虽然我还是不明白为什么不把代码放在 document.ready 里就不能修改 html 元素?
  • 从技术上讲,您不必使用$(document).ready() - 如果您的 JavaScript 包含在您正在使用的 HTML 元素之后,则您不必使用,因为通过浏览器访问 javascript 的时间已经“看到”了相关的 HTML。但是,如果您的 javascript 相关 HTML 之前出现,它将立即运行脚本,并且浏览器还没有“看到”该 html,这将导致错误。使用 jQuery 的 $(document).ready() 意味着您可以将您的 javascript 放在任何地方而不必担心这一点。希望有帮助
  • This answer 也可能有助于解释它。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    改为:

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

    【讨论】:

      【解决方案4】:

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

      希望这会有所帮助。

      【讨论】:

      • 这是我认为的最佳答案。 type="button" 从 HTML 文档的角度看得很清楚。不需要额外的 JS 操作。
      【解决方案5】:

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

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

      或按照其他答案的建议在表单提交上设置选择器(更好)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-14
        • 2015-08-19
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        相关资源
        最近更新 更多