R. Rajesh Jeba Anbiah wrote:
In IE, I could be able to directly refer the "id", but it isn't
possible in Firefox. Somewhere I read the solution is to refer the id
like document.getElementById("month") in Firefox. If I do so, the
script works well in Firefox, but IE throws error. (I have added the
code snippet below).
So, my question is: is there anyway to make the script work in all
browser *without* any browser fix ie, without adding any browser
detection check? Is this behavior is only for Firefox or any other
browsers also work like this (I don't have access to many browsers to
test)? TIA
<snippet>
<HEAD>
<SCRIPT LANGUAGE=javascript>
<script type="text/javascript">
<!--
function PopulateMonths()
{
//month is id used with select
But you also use name="month" in your code. So, there is a confusion
already here.
//month = document.getElementById("month"); //<-- for Firefox
month.options.length = 0; //clear options
for(var i=1; i<=12; ++i)
{
opt = new Option();
opt.text = i;
opt.value = i;
month.options[i-1] = opt;
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<!--month options-->
You need to insert <form action=""> element here.
<SELECT name="month" id="month">
</SELECT>
<!--calling script-->
<SCRIPT>
PopulateMonths(); //calling populate for the above options
</SCRIPT>
</BODY>
</snippet>
I would validate your HTML markup code first of all, preferably with a
strict doctype decl. because that will trigger MSIE 6 into web standards
compliant rendering mode.
List of valid DTDs you can use in your document.
http://www.w3.org/QA/2002/04/valid-dtd-list.html
Like someone else in the thread said, you first need to embed that
<select> inside a <form>. <form> also requires an action attribute.
Your populate select function could be streamlined a bit and clarified also:
function PopulateMonths()
{
var objMonthSelect;
if(document.getElementById)
{
objMonthSelect = document.getElementById("month");
}
else if(document.all && !document.getElementById) // MSIE 4 only
{
objMonthSelect = month;
};
objMonthSelect.options.length = 0; //clear options
for(var i=0; i<12; i++)
{
opt = new Option();
opt.text = i;
opt.value = i;
objMonthSelect.options[i] = opt;
};
}
You should also always use differential (and preferably meaningful)
identifiers for name attribute and id attribute for several reasons:
code reviewing by others, better discrimination of how your code
accesses nodes, better understanding of your code inner logic. <select
name="month" id="month"> just confuses the way certain browser actually
accesses nodes when one does
month.[some attribute]
Since above 96% of all browsers in use out there support flawlessly
getElementById method, then there is no problem with replacing
month
by
document.getElementById("month")
with proper object support for that method
Finally, I recommend you always call functions like PopulateMonths() on
the onload event of the body element, not as the document is being
parsed and rendered for several reasons.
DU