jQuery Forms

Write jQuery code to show the text typed in an input field

Description: Whatever the user types in the field must also appear in the paragraph below it, at once.

Hint:

  • Use the input event, .val() and .text().

HTML of the page

<input type="text" id="name" placeholder="Type your name">
<p>Hello, <span id="show"></span></p>

Solution

$('#name').on('input', function () {
  $('#show').text($(this).val());
});

$('#name').val('Anita').trigger('input');   // simulate the typing
HTML after the code runs

<p>Hello, <span id="show">Anita</span></p>

How it works

  • The input event fires on every change of the text, also when the user pastes.
  • We use .text() to show the value safely.

Read Mouse, Keyboard and Form Events.

Write jQuery code to validate that a field is not empty before submit

Description: If the name field is empty, stop the form and show the message “Name is required”.

Hint:

  • Use the submit event, e.preventDefault() and .val().trim().

HTML of the page

<form id="form">
  <input type="text" id="name" value="  ">
  <span id="error"></span>
  <button type="submit">Send</button>
</form>

Solution

$('#form').on('submit', function (e) {
  if ($('#name').val().trim() === '') {
    e.preventDefault();
    $('#error').text('Name is required');
  } else {
    $('#error').text('');
  }
});

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

Name is required

How it works

  • The field has only spaces, so after trim() it is empty.
  • preventDefault() stops the browser from sending the form.

Read jQuery Forms.

Write jQuery code to show the remaining characters of a textarea

Description: The textarea allows 50 characters. Show “N characters left” below it.

Hint:

  • Use the length of .val() in the input event.

HTML of the page

<textarea id="msg" maxlength="50"></textarea>
<p id="left">50 characters left</p>

Solution

var max = 50;

$('#msg').on('input', function () {
  var left = max - $(this).val().length;
  $('#left').text(left + ' characters left');
});

$('#msg').val('Hello jQuery world').trigger('input');
HTML after the code runs

<p id="left">32 characters left</p>

How it works

  • The text has 18 characters, so 32 are left.
  • The maxlength attribute in the HTML stops the typing at 50.

Read jQuery Forms.

Write jQuery code for a “select all” checkbox

Description: A master checkbox must check or uncheck all the item checkboxes. If one item is unchecked, the master must be unchecked.

Hint:

  • Use .prop('checked', ...) and compare the count of all and checked boxes.

HTML of the page

<input type="checkbox" id="all"> Select all
<input type="checkbox" class="item"> A
<input type="checkbox" class="item"> B
<input type="checkbox" class="item"> C

Solution

$('#all').on('change', function () {
  $('.item').prop('checked', this.checked);
});

$('.item').on('change', function () {
  var allChecked = $('.item:checked').length === $('.item').length;
  $('#all').prop('checked', allChecked);
});

$('#all').prop('checked', true).trigger('change');
console.log('checked items: ' + $('.item:checked').length);

$('.item').eq(1).prop('checked', false).trigger('change');
console.log('master checked: ' + $('#all').prop('checked'));
Console output

checked items: 3
master checked: false

How it works

  • The master sets the checked property of all items.
  • When one item changes, we compare the number of checked items with the total.

Read Get Content (attr vs prop).

Write jQuery code to filter a list while typing in a search box

Description: When the user types in the search box, show only the list items which contain the text. The search must not depend on upper or lower case.

Hint:

  • Use .toggle(condition) and indexOf() on lowercase text.

HTML of the page

<input type="text" id="search">
<ul id="names">
  <li>Anita</li>
  <li>Ravi</li>
  <li>Maya</li>
  <li>Manish</li>
</ul>

Solution

$('#search').on('input', function () {
  var term = $(this).val().toLowerCase();

  $('#names li').each(function () {
    var match = $(this).text().toLowerCase().indexOf(term) !== -1;
    $(this).toggle(match);
  });
});

$('#search').val('MA').trigger('input');
$('#names li').each(function () {
  console.log($(this).text() + ': ' + $(this).css('display'));
});
Console output

Anita: none
Ravi: none
Maya: list-item
Manish: list-item

How it works

  • The search text “MA” matches “Maya” and “Manish”.
  • .toggle(true) shows an element and .toggle(false) hides it.

Read jQuery each() and Effects.

Write jQuery code to enable the submit button only when a checkbox is checked

Description: The “Register” button must be disabled at the start, and enabled only when “I agree” is checked.

Hint:

  • Use .prop('disabled', ...) in the change event of the checkbox.

HTML of the page

<label><input type="checkbox" id="agree"> I agree to the terms</label>
<button id="register" disabled>Register</button>

Solution

$('#agree').on('change', function () {
  $('#register').prop('disabled', !this.checked);
});

console.log('start: disabled = ' + $('#register').prop('disabled'));

$('#agree').prop('checked', true).trigger('change');
console.log('checked: disabled = ' + $('#register').prop('disabled'));

$('#agree').prop('checked', false).trigger('change');
console.log('unchecked: disabled = ' + $('#register').prop('disabled'));
Console output

start: disabled = true
checked: disabled = false
unchecked: disabled = true

How it works

  • this.checked is true or false. We set disabled to the opposite.

Read Set Content (prop).

Write jQuery code to copy the text of one field to another field

Description: If the checkbox “Same as billing” is checked, copy the billing address into the shipping field. If it is unchecked, clear the shipping field.

Hint:

  • Use .val() as getter and setter and .is(':checked').

HTML of the page

<input type="text" id="billing" value="12 Main Road, Delhi">
<label><input type="checkbox" id="same"> Same as billing</label>
<input type="text" id="shipping" value="">

Solution

$('#same').on('change', function () {
  if ($(this).is(':checked')) {
    $('#shipping').val($('#billing').val());
  } else {
    $('#shipping').val('');
  }
});

$('#same').prop('checked', true).trigger('change');
console.log('shipping: "' + $('#shipping').val() + '"');

$('#same').prop('checked', false).trigger('change');
console.log('shipping: "' + $('#shipping').val() + '"');
Console output

shipping: "12 Main Road, Delhi"
shipping: ""

How it works

  • .val() without an argument reads the value, and with an argument it sets it.

Read Get Content and Set Content.