Monday, February 18, 2008

Javascript snippet

In my application, I need to modify a select dynamically. I found out inconsistency between IE and Firefox. In Firefox, property innerHTML can be used to set the content of a select object while it does not work in IE.

Following snippet works in Firefox:

var ele = document.getElementById('select1');
var htm = '<option value="coke">cokecola</option><option value="pepsi">Pepsi</option>';
ele.innerHTML = htm;

But it does not work in IE. You should use following snippet in IE:

var ele = document.getElementById('select1');
ele.options[0] = new Option('cokecola', 'coke');
ele.options[1] = new Option('Pepsi', 'pepsi');