Reputation: 829
I am unable to associate a datalist with an input using js, however I am able to if I manually add the list attribute using the document inspector in Chrome.
After doing a bit of research, I stumbled on the fact that the list property is read-only, http://msdn.microsoft.com/en-us/library/ie/hh772937(v=vs.85).aspx. Does this mean that it is impossible to associate a datalist using js or am I using the wrong property?
I am creating my inputs and datalists dynamically at runtime as part of a javascript library I am making so I am unable to attach the datalist in the normal way.
//Please open console
var myTextInput = document.getElementById('myTextInput'),
myDataList = document.getElementById('myDataList');
myTextInput.list = 'myDataList';
console.log(myTextInput.list); //Outputs: null
myTextInput.list = myDataList.id;
console.log(myTextInput.list); //Outputs: null
myTextInput.list = myDataList;
console.log(myTextInput.list); //Outputs: null
<form>
<input type="text" id="myTextInput" />
<datalist id="myDataList">
<option value="1" />
<option value="2" />
<option value="3" />
</datalist>
</form>
Upvotes: 1
Views: 834
Reputation: 12419
Use setAttribute()
- works for me in Firefox and Chrome:
myTextInput.setAttribute('list', 'myDataList');
I don't know if you have jQuery available, but if you do the jQuery version would be:
$(myTextInput).attr('list', 'myDataList');
Upvotes: 1