Simple jQuery Submission Form

Here’s a simple yet robust jQuery submission form. If you analyze the code for just a minute you can easily see how you can add more fields.




<form id="form" action="json/request.json">
  <div class="form-group">
     <label for="inputName">Name
     <input type="text" class="form-control" id="inputName" name="name">
  </div>
  <div class="form-group">
     <label for="inputEmail">Email
     <input type="email" class="form-control" id="inputEmail" name="email">
  </div>
  <div class="form-group">
     <label for="inputComment">Comment
     <textarea class="form-control" id="inputComment" name="comment" rows="6">
  </div>
    <button type="submit" class="btn btn-primary">Submit
</form>

Here’s the JavaScript needed to submit the form:

$(function () {
  var $body = $(document.body),
      $form = $('#form'),
      $name = $form.find('#inputName');

  $form.submitter({
    dataType: 'json',
    start: function (e) {
      if (!$name.val()) {
        e.preventDefault(); // Prevent submit
        $name.focus();

        // Tooltip: http:programming.sethharden.com
        $body.tooltip('Please enter a name', 'warning');
      }
    },
    done: function (e, data) {
      if ($.isPlainObject(data) && data.success) {
        $body.tooltip(data.result, 'success');
      }
    },
    fail: function (e, textStatus) {
      $body.tooltip(textStatus, 'danger');
    }
  });
});