jQuery Forms

Forms are a big part of a website. jQuery helps to read the fields, check them before sending, and submit the data with Ajax.

<form id="signup">
  <input type="text" name="name" value="Anita">
  <input type="email" name="email" value="anita@example.com">
  <select name="city">
    <option value="delhi" selected>Delhi</option>
    <option value="pune">Pune</option>
  </select>
  <input type="checkbox" name="news" value="yes" checked> Newsletter
  <input type="radio" name="plan" value="free"> Free
  <input type="radio" name="plan" value="pro" checked> Pro
  <textarea name="note">Hello</textarea>
  <button type="submit">Join</button>
</form>

Read field values

console.log($('[name=name]').val());
console.log($('[name=city]').val());
console.log($('[name=news]').is(':checked'));
console.log($('[name=plan]:checked').val());
console.log($('[name=note]').val());
Console output

Anita
delhi
true
pro
Hello

For radio buttons, select the checked one with :checked and then read its value.

serialize()

.serialize() makes a URL encoded string of all the fields of the form. It is ready to send with Ajax.

console.log($('#signup').serialize());
Console output

name=Anita&email=anita%40example.com&city=delhi&news=yes&plan=pro&note=Hello

serializeArray()

.serializeArray() gives an array of objects with the name and value of each field.

console.log($('#signup').serializeArray());
Console output

[
{ name: 'name', value: 'Anita' },
{ name: 'email', value: 'anita@example.com' },
{ name: 'city', value: 'delhi' },
{ name: 'news', value: 'yes' },
{ name: 'plan', value: 'pro' },
{ name: 'note', value: 'Hello' }
]

Fields without a name, disabled fields and unchecked checkboxes are not included.

Convert to a simple object

var data = {};
$.each($('#signup').serializeArray(), function (i, field) {
  data[field.name] = field.value;
});
console.log(data);
Console output

{
name: 'Anita',
email: 'anita@example.com',
city: 'delhi',
news: 'yes',
plan: 'pro',
note: 'Hello'
}

Validate a form before sending

<form id="login">
  <input type="text" id="user" name="user" value="">
  <input type="password" id="pass" name="pass" value="123">
  <p class="error"></p>
  <button type="submit">Login</button>
</form>
$('#login').on('submit', function (e) {
  var errors = [];

  if ($('#user').val().trim() === '') {
    errors.push('Username is required');
  }
  if ($('#pass').val().length < 6) {
    errors.push('Password must have at least 6 characters');
  }

  if (errors.length) {
    e.preventDefault();                       // stop the sending
    $('.error').text(errors.join('. '));
  }
});

$('#login').trigger('submit');
console.log($('.error').text());
Console output

Username is required. Password must have at least 6 characters

We use e.preventDefault() to stop the form when there are errors, and the native .trim() of strings.

Submit a form with Ajax

<form id="contact" action="send" method="post">
  <input type="text" name="name" value="Ravi">
  <input type="text" name="message" value="Hello there">
  <button type="submit">Send</button>
</form>
<p id="result"></p>
$('#contact').on('submit', function (e) {
  e.preventDefault();

  $.ajax({
    url: $(this).attr('action'),
    method: $(this).attr('method'),
    data: $(this).serialize(),
    dataType: 'json'
  }).done(function (res) {
    $('#result').text('Sent: ' + res.received);
  }).fail(function () {
    $('#result').text('Error');
  });
});

$('#contact').trigger('submit');
HTML after the code runs

<p id="result">Sent: name=Ravi&message=Hello+there</p>

Useful form methods

  • .val('text') sets a value. .val('') clears a field.
  • .prop('disabled', true) disables a field. Disable the submit button while the request is running.
  • $('form')[0].reset() resets the form with the native method.
  • The events focus, blur, change, input and submit are most used for forms.
Note: Always validate the data again on the server. The check in JavaScript is only for the comfort of the user, and everyone can skip it. Next: Utility Methods.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.