Re: OT: TECH: JavaScript help
From: | Mark J. Reed <markjreed@...> |
Date: | Tuesday, December 23, 2008, 1:04 |
On Mon, Dec 22, 2008 at 5:40 PM, Gary Shannon <fiziwig@...> wrote:
> My bad. Here's what I think he's after:
All this speculation! Where'd Benct go? Yoo-hoo! BPJ!
I don't like the decoupling of the initialization in that version: if
you change the order in one place, you have to remember to change it
in the other. This version does all the initialization via
Javascript, none in the HTML, so it can all be set together; the
disadvantage there is that it doesn't degrade gracefully if the user
doesn't have Javascript enabled.
<html>
<head>
<title>Test</title>
<script language="javascript" type="text/javascript">
(function () {
// For each option, 'key' is the value that will be sent as the value
// of the select list input if the form is submitted; 'label'
is the value
// that will be displayed to the user within the select list; and
// 'description' is what will show up in the separate text field. The
// order of the array below will be used for the select.
var options = [
{ 'key': 'tee', 'label': 'Tee!',
'description': 'long text for tee' },
{ 'key': 'tie', 'label': 'Tie!',
'description': 'longer text for tie' },
{ 'key': 'toe', 'label': 'Toe!',
'description': 'even longer text for toe' } ];
// We can't initialize things until the page is loaded, so we set an
// onload handler here to do it:
window.onload = function() {
// change 'myText' to the id of the text field input element
var textInput = document.getElementById('myText');
// change 'mySelect' to the id of the select list element
var selectList = document.getElementById('mySelect');
// build the select list from the options array above
if (textInput && selectList) {
for (var i=0; i<options.length; ++i) {
selectList.options[i] =
new Option(options[i].label, options[i].key);
}
}
// have the text field updated when the selected item changes
selectList.onchange = function() {
textInput.value = options[this.selectedIndex].description; }
// and call once to get the initial value
selectList.onchange();
// and prevent the user from typing in the text field
textInput.onkeypress = function() { return false; }
}
})();
</script>
</head>
<body>
<form>
<input id="myText" name="foo" />
<select id="mySelect" name="bar"></select>
</form>
</body>
</html>
--
Mark J. Reed <markjreed@...>