簡體   English   中英

表單提交按鈕onclick不會調用我的JS函數

[英]Form submit button onclick does not call my JS function

我有一個帶有提交按鈕的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直接從按鈕調用該函數,但是它不起作用。 我究竟做錯了什么 ?

 $('#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

    ...
}

使用帶有類型的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函數。

希望這可以幫助。

這些是您的問題:

  1. 將您的DOM讀取/操作代碼包裝在$(document).ready(function() { ... }); -確保元素可用於操縱。 請參閱指南
  2. 您將click事件綁定到了表單,而不是按鈕。
  3. 您需要使用event.preventDefault();取消表單提交的默認行為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"
    });
  });

});

這兒有個小提琴 它不會執行任何操作,但是當您單擊按鈕時,瀏覽器的控制台將顯示禁止的請求,表明正在嘗試發送數據。

您可以將選擇器設置為單擊按鈕

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

或在表單提交上設置選擇器(更好)作為建議的其他答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM