We help IT Professionals succeed at work.

How to populate datalist inside HTML5?

Whing Dela Cruz
on
Hi Experts, I want to populate datalist base on the var RX declared. I have three items that I want to populate it inside the Datalist. below is the code. All are inside the HTML. Any help please...

<!DOCTYPE HTML>
<html>
<head>
   
<script type="text/javascript">
    var RX = "Amoxicillin 500mg" + '\n' + "Cefalexin 250mg" + '\n' + "Cefuroxime 125mg";
</script>

</head>
   
<body>

<form>
<p>Datalist</p>
  <input list="Medicines" name="Anti-biotic">
  <datalist id="Medicines">
    <option value=RX>
  </datalist>
</form>
       
</body>
</html>
Comment
Watch Question

Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
http://jsbin.com/hamolijopi/1/edit?html,output
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <script>
    $(function() {
    var rx = ["Amoxicillin 500mg", "Cefalexin 250mg", "Cefuroxime 125mg"];
    var option = '';
    for (i = 0; i < rx.length; i++) {
        option += '<option value="' + rx[i] + '">' + rx[i] + '</option>';
    }
    $('#Medicines').append(option);
});
  </script>
  <meta charset="utf-8">
  <title>padas</title>
</head>
<body>
  <select id="Medicines"></select>
</body>
</html>

Open in new window

Author

Commented:
Hi scott Fell, its working. Could you provide me the code inside the  jquery specifically for this function. As I open the jquery huge of codes are there. I want to know what is specific function for this... Thanks!
Developer & EE Moderator
Fellow 2018
Most Valuable Expert 2013
Commented:
Jquery is very common in many sites.  Leave it in it's minimized form.   It does make it much easier for things like this.  But if you want pure js
http://jsbin.com/xanuzaquxi/2/edit
<!DOCTYPE html>
<html>
<head>

  <script>
 function start() {
 
    var rx = ["Amoxicillin 500mg", "Cefalexin 250mg", "Cefuroxime 125mg"];
    var option = '';
    for (i = 0; i < rx.length; i++) {
        option += '<option value="' + rx[i] + '">' + rx[i] + '</option>';
    }

   var select = document.getElementById('Medicines');
   select.innerHTML = select.innerHTML + option;
    }
  </script>
  <meta charset="utf-8">
  <title>padas</title>
</head>
<body onload="start()">
  <select id="Medicines"></select>
</body>
</html>

Open in new window

Author

Commented:
Thanks a lot Scott Fell, all are working.