Working With Dynamic Select Inside an Ajax Container

Posted by on Mon, December 11, 2006

▼ A d v e r t i s e m e n t

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):

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

The JavaScript:

<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);
// ]]>

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.

Related Posts with Thumbnails


Facebook Comment

WARNING & REMINDER: Comments are moderated and there is no exception. Comments unrelated to the post, too short, using phoney emails or funny names, will be marked as spam. Foul languages are filtered as spam. Your email will never be displayed on this site. If you would like to receive replies, use a valid email address and check the subscription box below.

Comments are closed.