Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the `list` attribute of an <input> in JavaScript

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

like image 835
John Williams Avatar asked Apr 19 '17 19:04

John Williams


People also ask

What is list attribute in input tag?

The list attribute refers to a <datalist> element that contains pre-defined options for an <input> element.

Can Javascript change HTML attribute values?

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.

Which attribute is used in input type to bind the data list to input?

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.


1 Answers

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 the list attribute. The property may be null 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>
like image 135
gyre Avatar answered Sep 19 '22 01:09

gyre