HTML | DOM Datalist options Collection
Last Updated :
20 Feb, 2019
The Datalist Options Collection is used to set or return the collection of all options value in a datalist. The elements in the collection are in sorted order.
Syntax:
datalistObject.options
Properties:
- length: It is used to return a number of <option> element in the collection. It is read only Property.
Methods: The DOM option collection contains three methods which are given below:
- [index]: It is used to return the element of the selected index. The index value starts from 0. It returns NULL if the index value is out of range.
- item(index): It is used to return the <option> element of selected index. The index value starts from 0. It returns NULL if the index value is out of range.
- namedItem(id): It is used to return the element from the collection with given id attribute. It returns NULL if the id is not valid.
Example-1: Returns option length value.
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green;font-size:39px;" >
GeeksForGeeks
</ h1 >
< h2 >DOM Datalist Option Collection</ h2 >
< form >
< label >Your Cars Name: </ label >
< input list = "gfg" >
< datalist id = "cars" >
< option value = "BMW" />
< option value = "Bentley" />
< option value = "Mercedes" />
< option value = "Audi" />
< option value = "Volkswagen" />
</ datalist >
</ form >
< br >
< button onclick = "myGeeks()" >Submit</ button >
< p id = "sudo" style = "font-size:20px;color:green;" ></ p >
< script >
function myGeeks() {
// Return length of option.
var g =
document.getElementById(
"cars").options.length;
document.getElementById("sudo").innerHTML =
"There are " + g + " options in the list.";
}
</ script >
</ center >
</ body >
</ html >
|
Output:
Before Clicking On Button:
After Clicking On Button:
Example-2: Returns the option’s value of a specific index.
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green;font-size:39px;" >
GeeksForGeeks
</ h1 >
< h2 >DOM Datalist Option Collection</ h2 >
< form >
< label >Your Cars Name: </ label >
< input list = "gfg" >
< datalist id = "cars" >
< option value = "BMW" />
< option value = "Bentley" />
< option value = "Mercedes" />
< option value = "Audi" />
< option value = "Volkswagen" />
</ datalist >
</ form >
< br >
< button onclick = "myGeeks()" >
Submit
</ button >
< p id = "sudo"
style = "font-size:20px;color:green;" >
</ p >
< script >
function myGeeks() {
// Return the value of index 2.
var g =
document.getElementById("cars").options[2].value;
document.getElementById("sudo").innerHTML =
g + " option is in 2nd index";
}
</ script >
</ center >
</ body >
</ html >
|
Output :
Before Clicking On Button:
After Clicking On Button:
Supported Browsers: The browser supported by DOM Datalist option Collection Property are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...