0

I am very VERY new to HTML/CSS/Javascript and stackoverflow. I'm trying to teach myself some user inputs. Currently, I'm stuck trying to use datalists.

Under my head tag I have successfully created an input that uses the datalist boxlist using HTML. Yay!

However, I have no idea how to make the inputs created on the button press (i.e created in the javascript addFields function) also use the boxlist datalist.

How can I get the newly created input fields to use the boxlist datalist? Is it possible to declare the datalist in javascript, and still have it used by the new fields?

        function addFields() {
            var input = document.createElement("input");
            document.body.appendChild(input);
        }
<head>
    <input name="box" list="boxlist" />
    <datalist id="boxlist">
        <option value="Item1"></option>
        <option value="Item2"></option>
        <option value="Item3"></option>
        <option value="Item4"></option>
    </datalist>
    <button type="button" onclick="addFields()">Add input</button>
</head>
LOTM
  • 3
  • 2
  • 2
    Don´t put any html elements in `` Body is the place to put those things! And the script tag should be in `head`. You should really start with a beginner guide, we cant teach you the fundamentals here. – el solo lobo Jan 08 '20 at 15:00
  • 1
    Does this answer your question? [Creating a HTML5 datalist on the fly](https://stackoverflow.com/questions/52397664/creating-a-html5-datalist-on-the-fly) – deblocker Jan 08 '20 at 15:06
  • Is what you want to achieve is, creating new `datalist` tag with same `options` when a button is pressed (in other words, *copy it*) – Anakin Jan 08 '20 at 15:09
  • Thanks for the advice @elsololobo. Looking at some guides right now. – LOTM Jan 09 '20 at 13:06
  • @deblocker thank you for the link! While it does contain the answer, Anakin made it much easier to understand. Thank you all! – LOTM Jan 09 '20 at 13:06

1 Answers1

0

Your code is almost working right, you just need to add the list attribute to the input you've created.

var element = document.createElement("input");
element.setAttribute("list", "boxlist");

Note:
It's better to wrap your input and datalist in a container, then append the input to the container. This way, it will be easier to manage afterwards.

Working fiddle: https://jsfiddle.net/Black3800/7kpqLg4z/

Anakin
  • 1,233
  • 1
  • 14
  • 20