Forum Moderators: open
<html>
<body>
<script type="text/javascript">
document.form.hr.value="02";
</script>
<form action="" method="post" name="form">
<label>Start Time:</label> *
<select id ="hr" name="hr">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
<option value="08">8</option>
<option value="09">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="00">12</option>
</select
</form>
</body>
</html> ...but that's not working at all. I think I have to do use document.form.hr.options[i].selected=true or something along those lines, but I'm not familiar enough with javascript to know for sure. Any suggestions?
And renaming the select... Instead of 'hr' (horizontal rule in HTML) try 'theHour'
Then... instead of
document.form.hr.value="02";
Try
document.myForm.theHour.selectedIndex = 1; // ONE, not TWO because OPTIONs are zero-based
I tried your suggestion, but I'm still getting the same problem...
Because . . . it loads top-down, and the form and select doesn't yet exist when you execute inline like that.
<script type="text/javascript">
window.onload= function () { document.myForm.theHour.selectedIndex = 1; };
</script>
I'm trying to take a value from a database...
This being the case, why don't you do something like this instead, releasing it from being Javascript dependent? A PHP sample,
$select = '<select name="' . $sel_name . '" id="' . $sel_name . '">';
$result = mysql_query(select * from table order by whatever");
while ($row = mysql_fetch_array($result)) {
$select .= '<option value="' . $row['value'] . '"';
if ($row['value'] == $input_variable) { $select .= ' selected'; }
$select .= '>' . $row['value'] . '</option>';
}
$select .= '</select>';
This leaves the select open for onChange events, if you need them . . . or no dependence at all.
window.onload is a little more smooth though, it does the same thing, doesn't execute the code until the page is entirely loaded. It allows you to put your link to the external JS in the head, where it's expected, then the functions in a separate file.
I have a function that is called in the onchange event of some form elements ... when the function was above the form, it wasn't called, but when I put it below the form, it worked fine.
Possibly an html error (do you validate [validator.w3.org] your documents?) which can cause JS to stumble, an error in the JS from moving it around, or some variable loading in the head that didn't get populated? Don't know. If it's a function that is called by some document action (link, button, submit) it should have worked either way.