Change the `list` <input> attribute in JavaScript
Trying to change input id: list from A to B, but not changing it.
I am planning to create a lot of datalist with PHP from MySQL,
Select a company name and see their employees in the following list.
HTML:
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
JAVASCRIPT:
function change() {
console.log("Started");
var x = document.getElementById('A').value;
document.getElementById('List').list = x;
var check = document.getElementById('List').list
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
Thanks, it works now.
source to share
According to the Mozilla Developer Network docs, the attribute list
is read-only and actually returns a reference to the DOM element (like a <datalist>
):
list
[ Read only ]
HTMLElement object
: Returns the element specified by the attributelist
. The property can benull
if the HTML element is not found in the same tree.
So you need to use setAttribute
to set the list id
and then use element.list.id
to get the correct value for check
.
function change() {
console.log("Started")
var x = document.getElementById('A').value
document.getElementById('List').setAttribute('list', x)
var check = document.getElementById('List').list.id
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
source to share
Since it is list
not a standard attribute, direct reference to the notation dot
will not work. Use getAttribute
and instead setAttribute
.
function change() {
console.log("Started");
var x = document.getElementById('C'),
list = document.getElementById('List'),
check = list.getAttribute(list);
list.setAttribute('list', x);
if (check === x.getAttribute('list')) {
console.log("Complete");
} else {
console.log("Failed");
}
}
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="C" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
source to share