Search code examples
jqueryhtmlsweetalert2html-datalist

How to dynamically create HTML input containing datalist using jQuery?


I have a HTML datalist that looks like this

<input type="text" list="cars" /> 
<datalist id="cars">
    <option>Volvo</option>
    <option>Saab</option>
    <option>Mercedes</option>
    <option>Audi</option>
</datalist>

Now I have a cars list

var carsList = ['Volvo', 'Saab', 'Mercedes', 'Audi']

Now I want to create the input field and datalist and fill it dynamically using jquery. So basically I want to create the above html snippet dynamically using jquery.

So this is what I do

 var carInput = document.createElement("input");
 carInput.type="text";
 carInput.list="cars";
 carInput.id = "carName"
 var carDatalist = document.createElement("datalist");
 carDatalist.id="cars";

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

But it only creates the input element and not the datalist element with it. What am I doing wrong?

EDIT: I want to create an independent html since I only want to use it on sweetalert2 popup and take input from the user.

This is what I show to the user. The popup only shows the input fieled but not the dropdown.

swal({
      title: 'Select a car name or define one',
      html: carInput,
      showCancelButton: true,
      width: '500px', 
      });

Solution

  • Created a template hidden div in order to be in DOM and then clone it with datalist appended:

    var carsList = ['Volvo', 'Saab', 'Mercedes', 'Audi'];
    
    $(".tmp").find("#cars").html("");
    $.each(carsList, function(i, item) {
        $(".tmp").find("#cars").append($("<option>").attr('value', i).text(item));
    });
    
    var div = $(".tmp").clone().show();
    
    Swal.fire({
      title: 'Select a car name or define one',
      html: div,
      showCancelButton: true,
      width: '500px', 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@9.5.4/dist/sweetalert2.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@9.5.4/dist/sweetalert2.all.min.js"></script>
    <div class="tmp" style="display: none;">
        <input type="text" list="cars" /> 
        <datalist id="cars">
        </datalist>
    </div>