Demo
Trying to change the input ID: List from A to B, but its not changing.
I am planning on creating many datalist with PHP from MySQL,
Select Company name, and see their employees in next 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");
}
}
Thank you, its now working.
Working
The list attribute refers to a <datalist> element that contains pre-defined options for an <input> element.
Javascript can be used to change the attribute(s) of a HTML element, such as a paragraph, a header, an image, or a list, or any various HTML elements. For example, by changing the src attribute of an img tag, we can change the image entirely to something else with Javascript.
To bind the <datalist> element to the control, we give it a unique identifier in the id attribute, and then add the list attribute to the <input> element with the same identifier as value.
According to the Mozilla Developer Network docs, the list
attribute is read-only and actually returns a reference to a DOM element (like a <datalist>
):
list
[Read only]
HTMLElement object
: Returns the element pointed by thelist
attribute. The property may benull
if no HTML element found in the same tree.
Thus, you need to use setAttribute
to set the list by id
, and then use element.list.id
to retrieve 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With