Get datalist options in IE9 with JavaScript

淺唱寂寞╮ 提交于 2019-12-05 02:21:33
Jordan Gray

IE 9 ignores option elements that aren't direct children of a select element (or an optgroup within one). A simple workaround is to wrap your option elements in a hidden select element using conditional comments:

<datalist id="languages">
<!--[if IE 9]><select disabled style="display:none"><![endif]-->
    <option value="Arabic">
    ...
<!--[if IE 9]></select><![endif]-->
</datalist>

Here's a jsFiddle demo of this approach.

2017 Update: It's worth noting that as of July 2017 Safari on iOS & Mac still haven't added support for <datalist> elements. OP asked for a solution that works will all major browsers so this probably isn't the best solution to that effect.

More info here: http://caniuse.com/#search=datalist

For some reason the solution provided did not work for me. Instead I used jQuery UI's autocomplete method and Modernizr to verify whether the browser supports it.

I ended up using this javascript code:

 var datalist, listAttribute, options = [];

if(!Modernizr.input.list)
{
    $('input[type="text"][list]').each(function() {
        listAttribute = $(this).attr('list');
        datalist = $('#' + listAttribute);
        if (datalist.length > 0) {
            options = [];
            datalist.find('option').each(function() {
                options.push({ label: this.innerHTML, value: this.value });
            });
            $(this).autocomplete({
                source: options
            });
        }
    });
    $('datalist').remove();
}

For the following HTML:

<div id="LocationSearch" class="col-xs-4 col-md-3">
    <input type="text" name="locations" list="locations">
    <datalist id="locations">
        <select name="locations">
            <option value="CD455">CD455</option>
            <option value="CD455">CD455</option>
            <option value="CD455">CD455</option>               
        </select>
    </datalist>
</div>

Used the following Microsoft post as a reference: http://msdn.microsoft.com/en-us/magazine/dn133614.aspx

You need to add a meta element defining the compatibility view of the content to IE8, and also, enable the dummy-element creation line - it's required as well.

So, your <head> should now look like this:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8"> <!-- IMPORTANT -->
<title>Datalist fetching in IE9</title>
<script type="text/javascript">
    document.createElement('datalist');          // IMPORTANT AS WELL
    window.onload = function() {
        alert(document.getElementById('languages').getElementsByTagName('option').length);//should alert 42
    };
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!