Wednesday, March 20, 2013

HTML 5 DataList Key Value Work Around

I like the new HTML 5 datalist element.  But most of the time when I deal with autocomplete drop down type stuff it is usually in key value pairs read from a database.  The datalist doesn't (too my knowledge) support this out of the box.  But you can add an attribute of say id to each option in your datalist, and then use a little jQuery to grab that id value for pushing back up to the server onsubmit.  Here is a basic example just to get you going.

 <!DOCTYPE html>  
 <html lang="en">  
     <meta charset="utf-8" />  
     <script src=""></script>  
     <form name="test" method="post" action="">  
     <input id="datalisttestinput" list="stuff" ></input>  
       <datalist id="stuff">  
         <option data-id="3" value="Collin" >  
         <option data-id="5" value="Carl">  
         <option data-id="1" value="Amy" >  
         <option data-id="2" value="Kristal">  
     <br /><br />  
       <a href="javascript:GetValue();">test</a>  
       function GetValue() {  
         var x = $('#datalisttestinput').val();  
         var z = $('#stuff');  
         var val = $(z).find('option[value="' + x + '"]');  
         var endval = val.attr('data-id');  
Update: You can also do <option value="3">Collin</option> like you would expect on some browsers, hopefully all soon.