Home > Back-end >  How to add (list) attribute to input element using Javascript?
How to add (list) attribute to input element using Javascript?

Time:01-15

I'm trying to create an input element in JS and attaching the (list) attribute to it using (setAttribute). Then created a datalist and fetched data values from the DB (two columns: species and genus) as shown in the PHP code. The problem is that the input element isn't displaying any of the retrieved data values.

<html>
    <head>
        <title>Sample Page</title>
    </head>
    <script>
    function createInput(){
    var container = document.getElementById("chatcontainer");
    var input = document.createElement("input");
    input.type = "text";
    input.setAttribute("name", "inputTest");
    input.setAttribute("placeholder", "Enter Text");
    input.required = true;
    input.setAttribute("list", "termList");
    input.setAttribute("style", "width:20%;");
    container.appendChild(input);
    }
</script>
    </head>
    <body>
        <div  id="chatcontainer">
            <button  onclick="createInput()">&nbsp;Create an input field</button>
            <datalist id="termList">
                <?php 
    require "db_connect.php"; // Database Connection 
    $d_list="(select species as Term from bioset) union (select distinct genus from bioset)";
    foreach ($conn->query($d_list) as $row) {
    echo "<option>";
    echo $row['Term'];
    echo "</option>";
    }            
    ?>
            </datalist>
        </div>
    </body>
</html>

CodePudding user response:

The way you do it seem to work, so, this means that the error is not with this code.

function createInput() {
  var container = document.getElementById("chatcontainer");
  var input = document.createElement("input");
  input.type = "text";
  input.setAttribute("name", "inputTest");
  input.setAttribute("placeholder", "Enter Text");
  input.required = true;
  input.setAttribute("list", "termList");
  input.setAttribute("style", "width:20%;");
  container.appendChild(input);
}
<div id="chatcontainer">
  <button onclick="createInput()">&nbsp;Create an input field</button>
  <datalist id="termList">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
  </datalist>
</div>

  •  Tags:  
  • Related