How to enable click in retrieved fragments

i have this contacts.txt (from notepad)

kate|female|kathryn bailey beckinsale|26-jul-1973|#23 underworld drive|(621) 142-7827|kate@lycans.net
jessica|female|jessica claire biel|03-mar-1982|27 texas avenue|(53)2344223|jbiel@yahoo.com
johnny|male|john christopher depp ii|09-jun-1963|711 pirate road|(773) 476-6634|jsparrow@piratebay.org

this is html and javascript:

<html>
	<head>
		<title>Practice</title>
		<link rel="stylesheet" type="text/css" title="Preferred" href="css.css"/>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		
		<script type="text/javascript">
			function syncText() {
				var xhr = new XMLHttpRequest();
				xhr.open("get", "data/contacts.txt", false);
				xhr.send(null);

			if (xhr.status == 200) {
				var data = xhr.responseText;
				var items = data.split("\
");
				items.sort();
				var frag = document.createDocumentFragment();
		
				for (i=0; i<items.length; i++){
					els = items[i].split("|");
					li = document.createElement("li");
					li.innerHTML = els[0];
					frag.appendChild(li);
														
				}
					document.getElementById("list").appendChild(frag);
					
			} else {
				alert("data retrieval failed...");
			}
			}
			
				
		</script>
		
		
	</head>
	
	<body onload="syncText()">
	
	
	<div id="header">
		<h1>My Contacts</h1>
		<img src="data/resources/contacts.png" alt="Contacts" />
	</div>
	
	<div>
		<h2>Contact List</h2>
	</div>	
	
	<div id="header2" style="overflow:scroll;">
        <ul id="list"></ul>
    </div>	
	
	<div>
		<h3>Contact Details</h3>
	</div >
	
	<div id="header3">
		<form>
			<table>
				<tr>
				<td>name:</td>
				<td><input type="text" id="ajaxName" name="name"><td>
				</tr>
				<tr>
				<td>birthday:</td>
				<td><input type="text" id="ajaxBday"name="bday"><td>
				</tr>
				<tr>
				<td>address:</td>
				<td><input type="text" id="ajaxAddress"name="address"><td>
				</tr>
				<tr>
				<td>phone: </td>
				<td><input type="text" id="ajaxPhone"name="phone"><td>
				</tr>
				<tr>
				<td>email:</td>
				<td><input type="text" id="ajaxEmail"name="email"><td>
				</tr>
			</table>
		</form>
	</div>
	
	</body>
</html>

the problem is how to be able to click the retrieved names and place it in the forms…

Hi there,

So, a couple of things:

  • In your next post, please use code tags. You can find them in the editor if you click “Go Advanced”. Then mark the code you wish to highlight and chose the correct syntax from the drop-down. Alternatively, there are short cuts for “code”, “php” and “HTML” on the right hand side of the second row. These work in much the same way.
  • Please don’t use tables for layout purposes, I have reworked your example using semantic tags.
  • As I recommended before, you will have a better time of things in the long run if you convert your script to use JSON or some other kind of key value notation.

Ok, with that said, here is a suggestion of how to do what you want:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Fetach AJAX example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      label{
        display:inline-block;
        width:65px;
        margin: 5px 0;
      }
      </style>
  </head>

  <body>
    <div id="header">
      <h1>My Contacts</h1>
    </div>
    
    <h2>Contact List</h2>
    
    <div id="header2">
      <ul id="list"></ul> 
    </div>  
    
    <div>
      <h3>Contact Details</h3>
    </div >
    
    <div id="header3">
      <form id="myForm">
        <div>
          <label for="ajaxName">Name:</label> 
          <input type="text" id="ajaxName" name="name"><td>
        </div>
        
        <div>
          <label for="ajaxBday">Birthday:</label> 
          <input type="text" id="ajaxBday" name="bday"><td>
        </div>
        
        <div>
          <label for="ajaxAddress">Address:</label> 
          <input type="text" id="ajaxAddress" name="address"><td>
        </div>
        
        <div>
          <label for="ajaxPhone">Phone:</label> 
          <input type="text" id="ajaxPhone" name="phone"><td>
        </div>
        
        <div>
          <label for="ajaxEmail">Email:</label> 
          <input type="text" id="ajaxEmail" name="email"><td>
        </div>
      </form>
    </div>
    
    <script type="text/javascript">
      function syncText() {
        var xhr = new XMLHttpRequest();
        xhr.open("get", "contacts.txt", false);
        xhr.send(null);
        if (xhr.status == 200) {
          processData((xhr.responseText).split("\
").sort());
        } else {
          alert("data retrieval failed...");
        }
      }
      
      function processData(t){
        frag = document.createDocumentFragment();
        for (i=0; i<t.length; i++){
          els = t[i].split("|");
          li = document.createElement("li");
          li.innerHTML = els[0];
          li.id = i;
          frag.appendChild(li);
        }
        document.getElementById("list").appendChild(frag);
        
        // This is ugly and could be written much better if we were working with key value pairs!!
        //
        f = document.getElementById("myForm");
        ul = document.getElementById("list");
        li = ul.getElementsByTagName("li");
        for (i = 0; i < li.length; ++i) {
          li[i].onclick = function(){
            els = t[this.id].split("|");
            console.log(els);
            f.name.value = els[0];
            f.bday.value = els[3];
            f.address.value = els[4];
            f.phone.value = els[5];
            f.email.value = els[6];
          }
        }
      }
      
      window.onload = syncText();
    </script>
  </body>
</html>

If there’s anything here you don’t understand, just let me know and I’ll be more than happy to explain what I’ve done.

im sorry… i’ll do better post next time… wow thankz… this is great… im so happy…

Cool!
If you’re happy, I’m happy :slight_smile:

Do you have control over the text file the data is loaded from?

I rewrote your script a little more.
The contacts should now be stored as JSON, like so:

{
   "contacts":[
      {
         "firstName":"Jessica",
         "middleName":"Claire",
         "lastName":"Biel",
         "sex":"female",
         "birthday":"03-mar-1982",
         "address":"27 texas avenue",
         "phone":"(53)2344223",
         "email":"jbiel@yahoo.com"
      },
      {
         "firstName":"Kate",
         "middleName":"Bailey",
         "lastName":"Beckinsdale",
         "sex":"female",
         "birthday":"26-jul-1973",
         "address":"#23 underworld drive",
         "phone":"(621) 142-7827",
         "email":"kate@lycans.net"
      },
      {
         "firstName":"Johnny",
         "middleName":"Christopher",
         "lastName":"Depp",
         "sex":"male",
         "birthday":"09-jun-1963",
         "address":"711 pirate road",
         "phone":"(773) 476-6634",
         "email":"jsparrow@piratebay.org"
      }
   ]
}

I broke up your script a little, gave the methods better names and generally tried to make the code more readable.
I also added a function that allows you to sort your contacts by any of the keys. In the example, I used “firstName”.

<!DOCTYPE HTML>
<html>
  <head>
    <!-- http://www.sitepoint.com/forums/showthread.php?977168-how-to-enable-click-in-retrieved-fragments -->
    <title>Fetach AJAX example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      label{
        display:inline-block;
        width:75px;
        margin: 5px 0;
      }
      </style>
  </head>

  <body>
    <div id="header">
      <h1>My Contacts</h1>
    </div>
    
    <h2>Contact List</h2>
    
    <div id="header2">
      <ul id="list"></ul> 
    </div>  
    
    <div>
      <h3>Contact Details</h3>
    </div >
    
    <div id="header3">
      <form name="myForm">
        <div>
          <label for="ajaxName">First name:</label> 
          <input type="text" id="ajaxName" name="firstName"><td>
        </div>
        
        <div>
          <label for="ajaxBday">Birthday:</label> 
          <input type="text" id="ajaxBday" name="birthday"><td>
        </div>
        
        <div>
          <label for="ajaxAddress">Address:</label> 
          <input type="text" id="ajaxAddress" name="address"><td>
        </div>
        
        <div>
          <label for="ajaxPhone">Phone:</label> 
          <input type="text" id="ajaxPhone" name="phone"><td>
        </div>
        
        <div>
          <label for="ajaxEmail">Email:</label> 
          <input type="text" id="ajaxEmail" name="email"><td>
        </div>
      </form>
    </div>
    
    <script type="text/javascript">
      function sortByKey(array, key) {
        return array.sort(function(a, b) {
          var x = a[key]; var y = b[key];
          return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
      }
      
      function populateContactList(contacts){
        frag = document.createDocumentFragment();
        for (i=0; i < contacts.length; i++){
          li = document.createElement("li");
          li.innerHTML = contacts[i].firstName;
          frag.appendChild(li);
        }
        document.getElementById("list").appendChild(frag);
      }
      
      function makeContactsClickable(contacts){
        ul = document.getElementById("list");
        li = ul.getElementsByTagName("li");
        var inputs = myForm.getElementsByTagName("input");
        
        for (i = 0; i < li.length; i++) {
          li[i].onclick = function(contact) {
            return function() {
              for (j=0; j < inputs.length; j++){
                attr = inputs[j].name;
                inputs[j].value = contact[attr];
              }
            }
          }(contacts[i]);
        }
      }
      
      function retrieveContacts() {
        var xhr = new XMLHttpRequest();
        xhr.open("get", "contacts_json.txt", false);
        xhr.send(null);
        if (xhr.status == 200) {
          json = JSON.parse(xhr.responseText);
          contacts = sortByKey(json.contacts, 'firstName');
          populateContactList(contacts);
          makeContactsClickable(contacts);
        } else {
          alert("data retrieval failed...");
        }
      }
      
      window.onload = retrieveContacts();
    </script>
  </body>
</html>

BTW, I lifted the sort function from StackOverflow: http://stackoverflow.com/questions/8175093/simple-function-to-sort-a-json-object-using-javascript

thankz… i hope you’ll answer my new post about local storage…