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.


Learn more about the similar topics:
Tutorials
jQuery Forms
Exercises & Assignments
Write jQuery code to validate that a field is not empty before submit
Write jQuery code to show the remaining characters of a textarea
Write jQuery code for a “select all” checkbox
Write jQuery code to enable the submit button only when a checkbox is checked
Write jQuery code to copy the text of one field to another field
Interview Questions & Answers
How do you get the value of an input, checkbox and radio button in jQuery?
How do you serialize a form in jQuery?