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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |