Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Forms: val and serialize

The value of any form field (a text input, a select, a textarea) is read and changed with val(). To collect all fields of a form at once, for example to send them to a server, there is serialize().

Reading and writing a value

<input id="title" value="Buy bread">
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  console.log($('#title').val()); // Buy bread
 
  $('#title').val('Call Oleg');
</script>

The field now says "Call Oleg". For a <select>, val() returns the selected option's value, and for a checkbox you need prop('checked') from the attributes lesson.

Handling submission

The course's form is a sign-up form. The handler goes on the form's submit event, not on the button click: submit fires however the form is sent, by the button or by Enter in a field.

<form id="signup">
  <input name="name" placeholder="Name">
  <input name="email" type="email" placeholder="Email">
  <select name="plan">
    <option value="free">Free</option>
    <option value="pro">Pro, $5 a month</option>
  </select>
  <label><input name="news" type="checkbox"> Send me news</label>
  <button>Sign up</button>
</form>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  $('#signup').on('submit', function (event) {
    event.preventDefault();
 
    const $form = $(this);
    console.log('Name:', $form.find('[name="name"]').val());
    console.log('Plan:', $form.find('[name="plan"]').val());
    console.log('News:', $form.find('[name="news"]').prop('checked'));
  });
</script>

Fill in the form and press the button: thanks to preventDefault() the page does not reload, and the field values appear in the output.

serialize: all fields as one string

serialize() collects the fields that have a name attribute into a query string, the same format the browser uses to submit a form:

<form id="signup">
  <input name="name" value="Anna">
  <input name="email" value="anna@example.com">
  <label><input name="news" type="checkbox" checked> Send me news</label>
</form>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  console.log($('#signup').serialize());
  // name=Anna&email=anna%40example.com&news=on
</script>

Special characters are encoded. Such a string can be passed straight to $.post(); see the AJAX lesson.

serializeArray: an array of pairs

serializeArray() returns an array of objects with name and value keys. It is easy to turn into a plain object:

<form id="signup">
  <input name="name" value="Anna">
  <input name="email" value="anna@example.com">
</form>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  const data = {};
  for (const field of $('#signup').serializeArray()) {
    data[field.name] = field.value;
  }
 
  console.log(data.name, data.email); // Anna anna@example.com
</script>

The same in plain JavaScript

val() corresponds to the value property. Instead of serialize() use new URLSearchParams(new FormData(form)).toString(), instead of serializeArray() use Object.fromEntries(new FormData(form)).

Common mistake

Forgetting the name attribute on a field. serialize() and serializeArray() skip fields without name, so they never reach the server. Disabled fields and unchecked checkboxes are skipped too.

Thanks for reading!

Donate to the site — we work hard for you.