Form submit button onclick does not call my JS function

☆樱花仙子☆ 提交于 2021-01-28 19:14:33

问题


I have an html form with a submit button. I have a js function in a file that I include in the head. I am trying to bind the onclick event of the button to call that function. However, all the methods I tried did not work.

<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>

The JS function is in 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"
   });
});

I also tried to call the function directly from the button with onclick but it did not work. What am I doing wrong ?


回答1:


These are your issues:

  1. Wrap your DOM reading/manipulating code in $(document).ready(function() { ... }); - this ensures the elements are available for manipulation. See guide.
  2. You were binding the click event to the form, not the button.
  3. You need to cancel the default behaviour of the form submit using event.preventDefault(); inside the event handler. See docs.

This edited code should work - please take the time to understand the changes written in comments:

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

});

There's a fiddle here. It won't do anything but your browser's console will show a forbidden request when you click the button, showing that an attempt to send the data is occurring.




回答2:


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



回答3:


Change to:

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

    ...
}



回答4:


Use an anchor tag or button with type but if you are using type="submit" ensure to event.preventDefault() in the beginning of the function call.

 <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(); ...} */

And one thing more if you are using a seperate file ensure it is loaded. So a better solution will be including the submit function in the html page itself.

Hope this helps.




回答5:


You can either set your selector on button click

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

or set the selector on form submit (which is better) as the other answers suggested



来源:https://stackoverflow.com/questions/35221978/form-submit-button-onclick-does-not-call-my-js-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!