Spider
Spider

Reputation: 915

Form submit button onclick does not call my JS function

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 ?

Upvotes: 1

Views: 2490

Answers (5)

Josh Harrison
Josh Harrison

Reputation: 5994

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.

Upvotes: 1

Moid
Moid

Reputation: 1447

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.

Upvotes: 1

Hussein Negm
Hussein Negm

Reputation: 601

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

Upvotes: 0

user5697101
user5697101

Reputation: 561

Change to:

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

    ...
}

Upvotes: 1

saikumar
saikumar

Reputation: 1051

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

Upvotes: 1

Related Questions