lukman lukman - 7 days ago 7
HTML Question

HTML select options not displaying when changed with JavaScript

I have two select elements created with basic HTML:

<div class="input-field col s12 m6 l6">
<select name="state" onchange="showLocalGovt(this.value)" class = 'validate'>
<option value="">Select your State</option>
<option value="Abia">Abia</option>
<option value="Adamawa">Adamawa</option>
<option value="Akwa Ibom">Akwa Ibom</option>
<label for="state">State</label>

<div class="row">
<div class="input-field col s12 m6 16">
<select id="LocalGovt" name="LocalGovt" class = 'validate'><option>Select Your Local Government</option></select>
<label for="LocalGovt">Select Your Local Government</label>

the way this is supposed to work is , depending on the state chosen , I'm using javascript to populate the second select element.

function showLocalGovt(str)


if (str=="")
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var local_govts =xmlhttp.responseText.split(',');
/*for(var i = 0;i<local_govts.length; i++)
document.getElementById('LocalGovt').options.add(new Option(local_govts[i], local_govts[i]));
for (var i = 0; i<local_govts.length; i++){
var opt = document.createElement('option');
opt.value = local_govts[i];
opt.innerHTML = local_govts[i];


The problem is the second select element doesn't get updated. I'm certain the JavaScript returns an array of the right values — I've confirmed with alerts. Also, when I use the Chrome developer tools, I can see the updated list of options. But it still doesn’t display on the webpage


I solved this by re-initializing the select element with materialize because it overrides the browser's default select elements


Found my answer here:

How to dynamically modify <select> in materialize css framework