1

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 ?

Spider
  • 875
  • 2
  • 9
  • 27

5 Answers5

1

$('#form_newCours').on('submit', function(){})
//use submit action on form element then callback will trigger
saikumar
  • 1,041
  • 6
  • 10
1

Change to:

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

    ...
}
user5697101
  • 571
  • 4
  • 12
1

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.

Moid
  • 1,447
  • 1
  • 13
  • 24
  • This is the best answer in my opinion. `type="button"` makes it clear from the HTML document perspective. No extra JS manipulation needed. – sargas Aug 25 '16 at 01:20
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.

Josh Harrison
  • 5,927
  • 1
  • 30
  • 44
  • Thank you Josh harrison. Your changes made it work. Though I still don't understand why we can't modify html elements if not putting the code in document.ready ? – Spider Feb 05 '16 at 14:22
  • 1
    Technically you don't have to use `$(document).ready()` - you wouldn't have to if your JavaScript is included _after_ the HTML elements that you are working with, because by the time the browser gets to the javascript it will already have "seen" the related HTML. But if your javascript comes _before_ the related HTML, it will run the script straight away and the browser will not yet have "seen" the html, which will cause errors. Using jQuery's `$(document).ready()` means you can put your javascript anywhere and not worry about this. Hope that helps – Josh Harrison Feb 05 '16 at 14:27
  • [This answer](http://stackoverflow.com/a/13062316/940252) may also help explain it. – Josh Harrison Feb 05 '16 at 14:28
0

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

Hussein Negm
  • 551
  • 5
  • 17