0

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 class="container" id="chatcontainer">
            <button class="btn fa fa-plus-circle" 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>

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. I had to place the PHP code in the head section before the script tag and it worked!
@MohammedAliMelhem order counts :) JS comes last (usually).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.