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">  
   <head>  
     <meta charset="utf-8" />  
     <title></title>  
     <script src="http://code.jquery.com/jquery-latest.min.js"></script>  
   </head>  
   <body>  
     <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">  
       </datalist>  
     <br /><br />  
       <a href="javascript:GetValue();">test</a>  
     </form>  
     <script>  
       function GetValue() {  
         var x = $('#datalisttestinput').val();  
         var z = $('#stuff');  
         var val = $(z).find('option[value="' + x + '"]');  
         var endval = val.attr('data-id');  
         alert(endval);  
       }  
     </script>  
   </body>  
 </html>  
Update: You can also do <option value="3">Collin</option> like you would expect on some browsers, hopefully all soon.

1 comment:

Eric Blanco said...

Perfect, dude, just what I was looking for. Thanks!