The Datalist
class represents an HTML <datalist> element.
Collection | Description |
---|---|
options | Returns all the options in a datalist |
The Datalist object supports the standard properties and events.
The following code shows how to get access a <datalist> element by using getElementById()
<!DOCTYPE html>
<html>
<body>
<form>
<input list="myDatalist">
<datalist id="myDatalist">
<option value="A">
<option value="B">
<option value="C">
<option value="D">
<option value="E">
</datalist>
</form><!--from w ww.ja v a 2s . c o m-->
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myDatalist").options.length;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to create a <datalist> element by using the document.createElement() method.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
</form><!-- ww w. j a v a 2 s. co m-->
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.createElement("INPUT");
x.setAttribute("list", "myList");
document.getElementById("myForm").appendChild(x);
var y = document.createElement("DATALIST");
y.setAttribute("id", "myList");
document.getElementById("myForm").appendChild(y);
var z = document.createElement("OPTION");
z.setAttribute("value", "A");
document.getElementById("myList").appendChild(z);
}
</script>
</body>
</html>
The code above is rendered as follows: