Dynamic HTML5 Datalist

33,971

Solution 1

I know this answer is late but it might help someone.

var nameArray = ["Rick Bross","Madison Smith","Jack Johnson"];

Add options to the datalist.
- "attr" helps if you need an i.d to identify each option.
- "text" is the content to be displayed.

$.each(nameArray, function(i, item) { $("#potentials").append($("<option>").attr('value', i).text(item)); });

Solution 2

There was a missing apostrophe, try:

$('#potentials').append("<option value='" + nameArray[i] + "'>");
Share:
33,971

Related videos on Youtube

Rick Bross
Author by

Rick Bross

I am a self-taught Web Developer turned Game Developer currently in New York City, New York. I am passionate about Javascript (jQuery, Backbone, Node and AngularJS) and HTML5 technologies. I'm interested in learning more about machine learning and artificial intelligence.

Updated on February 12, 2021

Comments

  • Rick Bross
    Rick Bross about 3 years

    So I am having a bit of an issue getting my HTML5 Datalist to populate dynamically from a javascript array that is being populated from values of a key of an object that is being populated via rows in a MySQL database. Phew!

    MySQL Database => Table => Rows => JSON => Javascript Objects => "firstname" & "lastname" key => Array of first names => Datalist Options.

    I successfully created the Array of names:

    var nameArray = ["Rick Bross","Madison Smith","Jack Johnson"]; //Example of my array
    

    And set up a loop to .append them to the datalist:

    for (var i = 0; i < nameArray.length; i++) {
        alert(i + " - " + nameArray[i]); //Works Fine, "0 - Rick Bross", "1 - Madison Smith", etc.
        $('#potentials').append("<option value='" + nameArray[i] + ">"); // Not working.
    }
    

    Here is my HTML:

    <input tabindex='1' list="potentials" type="text" placeholder="First &amp; Last Name" id="name" name="name"></input>
    <datalist id="potentials">
    </datalist>
    

    Why this isn't populating?

    • MarioDS
      MarioDS about 11 years
      +1 for a sscce-compliant question :)
  • Uyghur Lives Matter
    Uyghur Lives Matter over 9 years
    If $('#potentials') does not work, including the element type in the selector as $('datalist#potentials') will not help.