Working With Dynamic Select Inside an Ajax Container

I spent like half an hour on this, got tired, went out to The Curve Damansara, and tonight when I came back, tried a simple trick and it all worked.

I had a code similar to this (shortened for understanding):

1
2
3
4
5
<select id="distDst">
	<option value="1">Name of the option</option>
</select>
 
<input type="button" value="getSelected" onClick="getData()"/>

The JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
< ![CDATA[
 
function getData()
{
	distDst = document.getElementById('distDst');
	if(distDst.selectedIndex == -1) { alert('Please select an option.'); return; }
	else alert('Selected value: ' + distDst.options[distDst.selectedIndex].value);
}
 
// ]]>
</script>

All three browsers: IE 6, Firefox 2.0, and Opera 9.02 gave me an undefined value for the selected element (focused, of course).

When I came back, I added name="distDst" to line 01 of the first part, so Firefox and Opera agreed while IE is still stubborn. Next I enclosed the select object within form tags and IE yielded and gave me the results I want.

I don’t understand about IE’s problem, but why does Firefox and Opera requires the name= attribute to be added when I used getElementById not getElementByName? Still a mystery to me. If you put those code inside a single HTML file it would work. In my case those two would end up on the same page but the JavaScript would load first inside a container, and the HTML loads within another container. They are nested.

Well hope this helps anyone trying to implement select objects with JavaScripts inside AJAX containers.

Sorry for the technicality. I am now implementing AJAX front-ends for my PHP codes, after I got bored with conventional PHP programming.

I forgot to mention: The problem only occurs when the dynamic select object have 1 item in the list.

0 Shares