Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set HTML5 input list value with JavaScript

I'm to create a html5 input field with an attached datalist by JavaScript. I'm not having any issues creating these dom nodes, but I am having trouble setting the list attribute value using pure JavaScript. Is this possible? I've checked the functionality of the node and the value of list is there, but whenever I try and set it no new value is assigned. Does anybody have any ideas?

Here's an example in code.

var _form = document.body.appendChild(document.createElement('form')),
    _input = _form.appendChild(document.createElement('input')),
    _datalist = _form.appendChild(document.createElement('datalist'));

_input.list = 'exampleList';
_input.datalist_id = 'exampleList';
_input.className = 'getme';

_datalist.id = 'exampleList';

for (var i = 0; i < 5; i++) {
    var _option = _datalist.appendChild(document.createElement('option'));
    switch(i){
        case i:
            _option.value = i;
            break;
    };
};

Edit

I have found a method of doing this via the element.setAttribute(); method. How would one go about doing this in a syntax similar to (for example) element.className = 'value';.

Thank you in advance!

like image 629
lindsay Avatar asked Jul 24 '14 04:07

lindsay


1 Answers

According to MDN there is no property to set that attridute directly. So it looks like you're stuck with setAttribute()

You should also note that DOM manipulations come with some performance ovehead so it is some times best to minimise them. You might want to consider the following:

var _form = document.body.appendChild(document.createElement('form')),
    _input = _form.appendChild(document.createElement('input')),
    _datalist = _form.appendChild(document.createElement('datalist'));


_datalist.id = 'exampleList';
_input.setAttribute('list','exampleList');

var _option = "";
for (var i = 0; i < 5; i++) {
    _option += "<option value='" + i + "' />";
};

_datalist.innerHTML = _option;

Demo

like image 79
Jon P Avatar answered Oct 17 '22 07:10

Jon P