Another quick jQuery tutorial! Here’s the demo.

I’m building an app that requires members to “invite” contacts for each new record they create. (This consists primarily of a name and email address.) In some cases the contacts will be invited several times. So, in lieu of having the user re-enter information on multiple occasions I store previously invited users in a mySql table, and then render them in a select list. As far as UX goes this allows members to enter a new name and email address combination, or, select from a dropdown of previous users, in turn auto-populating the input fields. (Which makes validation cleaner.)

The jQuery library, in combination with some basic javascript, allows me to easily replace input values onChange.

The Javascript

We start by creating an array of the users associated with the member in question, in essence “My Contacts”. In each case the array key is the ID of the user from the mySql table. This makes posting and parsing the information easier. Note that we start by creating an empty record with the key “0″, this serves as a “reset” in the select list.

<script type="text/javascript">
  var peeps=[];
  peeps[0]=['',''];
  peeps[12]=['Joe Smith','joe@yahoo.com'];
  peeps[22]=['Bill Tester','bill@gmail.com'];
  peeps[58]=['Frank Jones','frank@hotmail.com'];
</script>

The HTML

Next,  we create our select list and our input fields. Note that the value of each option element is the ID of the user as identified in the array we created, and, the first option is set to 0, which fires our reset.

<select id="contacts">
  <option value="0">Choose One</option>
  <option value="12">Joe Smith</option>
  <option value="22">Bill Tester</option>
  <option value="58">Frank Jones</option>
</select>
<label>Contact Name:</label>
<input type="text" id="name" />
<label>Contact Email:</label>
<input type="text" id="email" />

The jQuery

Finally, we need to add our jQuery function. All we really do is reference the ID from the select list to our array, and in doing so, we change the value of our two input boxes via their id’s. (#name, #email)

<script type="text/javascript">
  $(function()
  {
    $('#contacts').change(function()
    {
      var dateRange=peeps[$(this).val()];
      $('#name').val(dateRange[0]);
      $('#email').val(dateRange[1]);
    });
  });
</script>

And that’s it! Here’s the demo.