Convert Figma logo to code with AI

jquery-form logoform

jQuery Form Plugin

5,197
2,149
5,197
35

Top Related Projects

jQuery Validation Plugin library sources

Semantic is a UI component framework based around useful principles from natural language.

A frontend Framework for single-page applications on top of REST/GraphQL APIs, using TypeScript, React and Material Design

JavaScript powered Forms with JSON Form Builder

27,910

A rugged, minimal framework for composing JavaScript behavior in your markup.

Quick Overview

jQuery Form is a popular plugin for the jQuery JavaScript library that enhances HTML forms with AJAX submissions, file uploads, and other advanced features. It simplifies the process of handling form submissions and provides a seamless user experience without page reloads.

Pros

  • Easy integration with existing jQuery projects
  • Supports both AJAX form submissions and traditional form submissions
  • Handles file uploads with progress tracking
  • Extensive customization options and callbacks

Cons

  • Requires jQuery as a dependency
  • May be considered outdated for modern web development practices
  • Limited support for more complex form scenarios
  • Potential performance overhead for large applications

Code Examples

  1. Basic AJAX form submission:
$('#myForm').ajaxForm({
    success: function(response) {
        alert('Form submitted successfully!');
    }
});
  1. File upload with progress tracking:
$('#uploadForm').ajaxForm({
    beforeSend: function() {
        var percentVal = '0%';
        $('.progress-bar').width(percentVal);
        $('.percent').html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        $('.progress-bar').width(percentVal);
        $('.percent').html(percentVal);
    },
    complete: function(xhr) {
        alert('File uploaded successfully!');
    }
});
  1. Form validation before submission:
$('#myForm').ajaxForm({
    beforeSubmit: function(arr, $form, options) {
        if ($form.find('input[name="email"]').val() == '') {
            alert('Please enter your email address');
            return false;
        }
        return true;
    }
});

Getting Started

To use jQuery Form in your project, follow these steps:

  1. Include jQuery and jQuery Form in your HTML:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
  1. Initialize the plugin on your form:
$(document).ready(function() {
    $('#myForm').ajaxForm({
        success: function(response) {
            console.log('Form submitted successfully');
        }
    });
});
  1. Customize the form submission behavior using the various options and callbacks provided by the plugin.

Competitor Comparisons

jQuery Validation Plugin library sources

Pros of jquery-validation

  • More comprehensive validation rules and methods
  • Better support for custom validation methods
  • Extensive documentation and examples

Cons of jquery-validation

  • Larger file size and potentially higher performance overhead
  • More complex setup for basic form validation scenarios

Code Comparison

jquery-validation:

$("#myform").validate({
  rules: {
    name: "required",
    email: {
      required: true,
      email: true
    }
  },
  messages: {
    name: "Please enter your name",
    email: "Please enter a valid email address"
  }
});

form:

$("#myform").ajaxForm({
  beforeSubmit: function(arr, $form, options) {
    // Perform validation here
    return $("#myform").valid();
  },
  success: function(response) {
    // Handle successful submission
  }
});

jquery-validation focuses on client-side form validation, offering a wide range of built-in validation rules and methods. It provides a more structured approach to form validation but may be overkill for simple forms.

form, on the other hand, is primarily designed for easy AJAX form submissions. While it doesn't provide built-in validation, it can be integrated with custom validation logic or other validation libraries.

Choose jquery-validation for complex form validation requirements, and form for simpler AJAX form submissions with custom validation needs.

Semantic is a UI component framework based around useful principles from natural language.

Pros of Semantic-UI

  • Comprehensive UI framework with a wide range of components and themes
  • Responsive design and mobile-first approach
  • Extensive documentation and community support

Cons of Semantic-UI

  • Larger file size and potential performance impact
  • Steeper learning curve due to its extensive features
  • Less focused on form handling specifically

Code Comparison

Semantic-UI (form creation):

<form class="ui form">
  <div class="field">
    <label>Name</label>
    <input type="text" name="name" placeholder="Enter your name">
  </div>
  <button class="ui button" type="submit">Submit</button>
</form>

Form (form submission):

$('#myForm').ajaxForm({
    url: 'submit.php',
    type: 'post',
    success: function(response) {
        console.log('Form submitted successfully');
    }
});

Key Differences

  • Semantic-UI is a full-featured UI framework, while Form focuses specifically on form handling and AJAX submissions
  • Form provides more advanced form-specific features like file uploads and form validation
  • Semantic-UI offers a wider range of UI components beyond forms
  • Form is lighter and more focused, while Semantic-UI provides a complete design system

Use Cases

  • Choose Semantic-UI for comprehensive UI development with consistent design
  • Opt for Form when you need advanced form handling and AJAX submissions in existing projects

A frontend Framework for single-page applications on top of REST/GraphQL APIs, using TypeScript, React and Material Design

Pros of react-admin

  • Comprehensive solution for building admin interfaces with React
  • Rich set of pre-built components and features for data management
  • Supports modern React patterns and practices

Cons of react-admin

  • Steeper learning curve due to its complexity and React-specific architecture
  • May be overkill for simple form handling or smaller projects
  • Requires more setup and configuration compared to form

Code Comparison

react-admin:

import { Admin, Resource } from 'react-admin';
import { PostList, PostEdit, PostCreate } from './posts';

const App = () => (
  <Admin dataProvider={...}>
    <Resource name="posts" list={PostList} edit={PostEdit} create={PostCreate} />
  </Admin>
);

form:

$('#myForm').ajaxForm({
  url: 'submit.php',
  type: 'post',
  success: function(response) {
    console.log('Form submitted successfully');
  }
});

Summary

react-admin is a full-featured admin panel framework for React applications, offering a wide range of components and tools for building complex data management interfaces. It's well-suited for large-scale applications but may be excessive for simpler projects.

form, on the other hand, is a lightweight jQuery plugin focused specifically on AJAX form submissions. It's easier to integrate into existing projects and requires less setup, but lacks the advanced features and React integration of react-admin.

Choose react-admin for comprehensive admin interfaces in React applications, and form for quick and easy AJAX form handling in jQuery-based projects.

JavaScript powered Forms with JSON Form Builder

Pros of formio.js

  • More comprehensive form-building solution with a drag-and-drop form builder
  • Supports complex form structures and advanced form components
  • Built-in API integration and data management capabilities

Cons of formio.js

  • Steeper learning curve due to its extensive features
  • Larger file size and potentially higher performance overhead
  • May be overkill for simple form handling needs

Code Comparison

form:

$('#myForm').ajaxForm({
    url: 'submit.php',
    type: 'post',
    success: function(response) {
        console.log('Form submitted successfully');
    }
});

formio.js:

Formio.createForm(document.getElementById('formio'), {
    components: [
        { type: 'textfield', key: 'firstName', label: 'First Name' },
        { type: 'textfield', key: 'lastName', label: 'Last Name' },
        { type: 'button', action: 'submit', label: 'Submit' }
    ]
}).then(function(form) {
    form.on('submit', function(submission) {
        console.log('Form submitted', submission);
    });
});

The code comparison illustrates the difference in approach between the two libraries. form focuses on enhancing existing HTML forms with AJAX submission, while formio.js provides a more programmatic way to create and manage forms, including form rendering and submission handling.

27,910

A rugged, minimal framework for composing JavaScript behavior in your markup.

Pros of Alpine

  • Lightweight and minimal, with a smaller footprint than jQuery
  • Modern approach to reactive UI, aligning with current web development trends
  • Can be used without a build step, making it easier to integrate into existing projects

Cons of Alpine

  • Less mature ecosystem and community compared to jQuery
  • Limited functionality out-of-the-box, may require additional libraries for complex form handling
  • Steeper learning curve for developers familiar with jQuery's imperative style

Code Comparison

Alpine:

<form x-data="{ name: '' }" x-on:submit.prevent="submitForm()">
  <input x-model="name" type="text">
  <button type="submit">Submit</button>
</form>

Form:

<form id="myForm">
  <input name="name" type="text">
  <button type="submit">Submit</button>
</form>
<script>
$('#myForm').ajaxForm({ /* options */ });
</script>

Summary

Alpine offers a modern, lightweight approach to building interactive UIs, while Form provides robust form handling capabilities within the jQuery ecosystem. Alpine excels in simplicity and reactivity, whereas Form benefits from jQuery's extensive plugin ecosystem and familiar API. The choice between them depends on project requirements, existing codebase, and developer preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

jQuery Form Build Status

Overview

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allow you to have full control over how the data is submitted.

No special markup is needed, just a normal form. Submitting a form with AJAX doesn't get any easier than this!

Community

Want to contribute to jQuery Form? Awesome! See CONTRIBUTING for more information.

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct to ensure that this project is a welcoming place for everyone to contribute to. By participating in this project you agree to abide by its terms.

Pull Requests Needed

Enhancements needed to to be fully compatible with jQuery 3

jQuery 3 is removing a lot of features that have been deprecated for a long time. Some of these are still in use by jQuery Form.
Pull requests and assistance in updating jQuery Form to be compatible with jQuery 3 are greatly appreciated.
See issue #544 for more information.

Compatibility

  • Requires jQuery 1.7.2 or later.
  • Compatible with jQuery 2.
  • Partially compatible with jQuery 3.
  • Not compatible with jQuery 3 Slim. (issue #544)

Download

CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>

or

<script src="https://cdn.jsdelivr.net/gh/jquery-form/form@4.3.0/dist/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>

API

jqXHR

The jqXHR object is stored in element data-cache with the jqxhr key after each ajaxSubmit call. It can be accessed like this:

var form = $('#myForm').ajaxSubmit({ /* options */ });
var xhr = form.data('jqxhr');

xhr.done(function() {
...
});

ajaxForm( options )

Prepares a form to be submitted via AJAX by adding all of the necessary event listeners. It does not submit the form. Use ajaxForm in your document's ready function to prepare existing forms for AJAX submission, or with the delegation option to handle forms not yet added to the DOM.
Use ajaxForm when you want the plugin to manage all the event binding for you.

// prepare all forms for ajax submission
$('form').ajaxForm({
    target: '#myResultsDiv'
});

ajaxSubmit( options )

Immediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. Use ajaxSubmit if you want to bind your own submit handler to the form.

// bind submit handler to form
$('form').on('submit', function(e) {
    e.preventDefault(); // prevent native submit
    $(this).ajaxSubmit({
        target: '#myResultsDiv'
    })
});

Options

Note: All standard $.ajax options can be used.

beforeSerialize

Callback function invoked before form serialization. Provides an opportunity to manipulate the form before its values are retrieved. Returning false from the callback will prevent the form from being submitted. The callback is invoked with two arguments: the jQuery wrapped form object and the options object.

beforeSerialize: function($form, options) {
    // return false to cancel submit
}

beforeSubmit

Callback function invoked before form submission. Returning false from the callback will prevent the form from being submitted. The callback is invoked with three arguments: the form data in array format, the jQuery wrapped form object, and the options object.

beforeSubmit: function(arr, $form, options) {
    // form data array is an array of objects with name and value properties
    // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
    // return false to cancel submit
}

beforeFormUnbind

Callback function invoked before form events unbind and bind again. Provides an opportunity to manipulate the form before events will be remounted. The callback is invoked with two arguments: the jQuery wrapped form object and the options object.

beforeFormUnbind: function($form, options) {
    // your callback code
}

filtering

Callback function invoked before processing fields. This provides a way to filter elements.

filtering: function(el, index) {
    if ( !$(el).hasClass('ignore') ) {
        return el;
    }
}

clearForm

Boolean flag indicating whether the form should be cleared if the submit is successful

data

An object containing extra data that should be submitted along with the form.

data: { key1: 'value1', key2: 'value2' }

dataType

Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType option provides a means for specifying how the server response should be handled. This maps directly to jQuery's dataType method. The following values are supported:

  • 'xml': server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value
  • 'json': server response will be evaluated and passed to the 'success' callback, if specified
  • 'script': server response is evaluated in the global context

delegation

true to enable support for event delegation requires jQuery v1.7+

// prepare all existing and future forms for ajax submission
$('form').ajaxForm({
    delegation: true
});

error

Deprecated
Callback function to be invoked upon error.

forceSync

Only applicable when explicity using the iframe option or when uploading files on browsers that don't support XHR2. Set to true to remove the short delay before posting form when uploading files. The delay is used to allow the browser to render DOM updates before performing a native form submit. This improves usability when displaying notifications to the user, such as "Please Wait..."

iframe

Boolean flag indicating whether the form should always target the server response to an iframe instead of leveraging XHR when possible.

iframeSrc

String value that should be used for the iframe's src attribute when an iframe is used.

iframeTarget

Identifies the iframe element to be used as the response target for file uploads. By default, the plugin will create a temporary iframe element to capture the response when uploading files. This option allows you to use an existing iframe if you wish. When using this option the plugin will not attempt handling the response from the server.

method

The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').

replaceTarget

Optionally used along with the target option. Set to true if the target should be replaced or false if only the target contents should be replaced.

resetForm

Boolean flag indicating whether the form should be reset if the submit is successful

semantic

Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the normal form serialization is done in semantic order except for input elements of type="image". You should only set the semantic option to true if your server has strict semantic requirements and your form contains an input element of type="image".

success

Deprecated
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following standard jQuery arguments:

  1. data, formatted according to the dataType parameter or the dataFilter callback function, if specified
  2. textStatus, string
  3. jqXHR, object
  4. $form jQuery object containing form element

target

Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element.

type

The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').
An alias for method option. Overridden by the method value if both are present.

uploadProgress

Callback function to be invoked with upload progress information (if supported by the browser). The callback is passed the following arguments:

  1. event; the browser event
  2. position (integer)
  3. total (integer)
  4. percentComplete (integer)

url

URL to which the form data will be submitted.


Utility Methods

formSerialize

Serializes the form into a query string. This method will return a string in the format: name1=value1&name2=value2

var queryString = $('#myFormId').formSerialize();

fieldSerialize

Serializes field elements into a query string. This is handy when you need to serialize only part of a form. This method will return a string in the format: name1=value1&name2=value2

var queryString = $('#myFormId .specialFields').fieldSerialize();

fieldValue

Returns the value(s) of the element(s) in the matched set in an array. This method always returns an array. If no valid value can be determined the array will be empty, otherwise it will contain one or more values.

resetForm

Resets the form to its original state by invoking the form element's native DOM method.

clearForm

Clears the form elements. This method empties all of the text inputs, password inputs and textarea elements, clears the selection in any select elements, and unchecks all radio and checkbox inputs. It does not clear hidden field values.

clearFields

Clears selected field elements. This is handy when you need to clear only a part of the form.


File Uploads

The Form Plugin supports the use of XMLHttpRequest Level 2 and FormData objects on browsers that support these features. As of today (March 2012) that includes Chrome, Safari, and Firefox. On these browsers (and future Opera and IE10) files uploads will occur seamlessly through the XHR object and progress updates are available as the upload proceeds. For older browsers, a fallback technology is used which involves iframes. More Info


Contributors

This project has transferred from github.com/malsup/form, courtesy of Mike Alsup.
See CONTRIBUTORS for details.

License

This project is dual-licensed under the LGPLv2.1 (or later) or MIT licenses:


Additional documentation and examples for version 3.51- at: http://malsup.com/jquery/form/

NPM DownloadsLast 30 Days