2016-02-05 127 views
1

我有一个提交按钮的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按钮调用函数,但没有奏效。我究竟做错了什么 ?

+1

不要使用'type submit'使用'type button' – guradio

+0

你将绑定到表单,尝试将它绑定到按钮并将它包装在[$(document).ready](https://learn.jquery .com /使用jQuery的核心/文件就绪/) –

+0

我没有看到一个onclick事件被称为.. ??在哪里试图访问此功能..? –

回答

1

这些是你的问题:

  1. 包装你的DOM读/在$(document).ready(function() { ... });操控代码 - 这确保了元件可用于操纵。 See guide
  2. 您将click事件绑定到窗体,而不是按钮。
  3. 您需要在事件处理函数内部使用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。它不会执行任何操作,但是当您单击该按钮时,浏览器的控制台将显示禁止的请求,表明正在尝试发送数据。

+0

谢谢乔希哈里森。您的更改使其工作。虽然我仍然不明白为什么我们不能修改html元素,如果没有把代码放在document.ready中? – Spider

+1

从技术上讲,你不必使用'$(document).ready()' - 如果你的JavaScript被包括在你正在使用的HTML元素之后,你不必这样做,因为在浏览器到达JavaScript将已经“看到”相关的HTML。但是,如果您的JavaScript在相关的HTML之前出现,它将马上运行该脚本,并且浏览器将不会“看到”该HTML,这将导致错误。使用jQuery的'$(document).ready()'意味着你可以把你的javascript放在任何地方,而不用担心这一点。希望有助于 –

+0

[这个答案](http://stackoverflow.com/a/13062316/940252)也可能有助于解释它。 –

1

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

0

您可以将您的按钮选择点击

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

或设置形式选择提交(这是更好)的其他答案建议

1

更改为:

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

    ... 
} 
1

使用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页面中包含submit函数。

希望这会有所帮助。

+0

这在我看来是最好的答案。从HTML文档的角度来看,'type =“button”'表示清楚。不需要额外的JS操作。 – sargas