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',
});
$('#cars')with the variable for the datalist you just created.$("#cars")is the id for the datalist? So I target that. and fill it up.$(<selector>)is going to look for matching elements in the DOM. As you have not appended the datalist you just made to the DOM yet, it will not find it. Further more, since you already have the variable with a reference to it, trying to find it is pointless.carDatalist.innerHTML += '...yourhtml...'or$(carDatalist).append(...