Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

574 CHAPTER 15 Local data with web storage


var html = '';
for (var i = 0; i < results.length; i++) {
var contact = results[i];
html += '<tr><td>' + contact.email + '</td>';
html += '<td>' + contact.firstName + ' ' + contact.lastName + '</td>';
html += '<td><a class="edit" href="javascript:void(0)" data-key='
+ i + '>Edit</a></td></tr>';
}
html = html || '<tr><td colspan="3">No records available</td></tr>';
$('#contacts tbody').html(html);
}
You created the edit link for each row; now you create the methods needed to display
the details for the selected row.
Because the method is invoked by clicking the link, you can get the index of the item
by inspecting the data-key attribute on the this object.


  1. Use the index to find the corresponding item in the contacts array and then store the
    index and contact object within the currentRecord field.
    You will call a displayCurrentRecord method, which you create in the next step. Your
    code should look like the following.
    ns.loadContact = function () {
    var key = parseInt($(this).attr('data-key'));
    var results = retrieveFromStorage();
    $('#currentAction').html('Edit Contact');
    currentRecord = { key: key, contact: results[key] }
    displayCurrentRecord();
    };

  2. Add the displayCurrentRecord method, which populates the form fields with contact
    information as follows.
    function displayCurrentRecord() {
    var contact = currentRecord.contact;
    $('#firstName').val(contact.firstName);
    $('#lastName').val(contact.lastName);
    $('#email').val(contact.email);
    $('#phoneNumber').val(contact.phoneNumber);
    }

  3. In the bindToGrid method that you created earlier, add the following line to the end of
    the method.
    This binds the click event of the Edit links to the loadContact method.
    $('#contacts a.edit').on('click', ns.loadContact);

  4. Update the display method to instantiate an empty default currentRecord object that
    is used to add a contact as follows.
    ns.display = function () {
    $('#currentAction').html('Add Contact');
    currentRecord = { key: null, contact: {} };

Free download pdf