View Full Version : Noob JS question... about the global namespace

Dec 17th, 2009, 06:47 PM
Could someone please change this line so that it respects the global namespace:

var selected = students.options[students.selectedIndex].value;

The error console is telling me to use document.getElementById but I don't know where to put it.


Dec 17th, 2009, 07:32 PM
Figured it out :D

var test = document.getElementById('students')
var selected = test.options[test.selectedIndex].value;

Old Pedant
Dec 17th, 2009, 07:34 PM
Well, "students" is the name of some <select>, so it's part of some <form>.

So the right way might be to do:

var students = document.NameOfThatForm.students;
var selected = students.options[students.selectedIndex].value;

Now, it's possible that "students" is *NOT* the name of the <select>. Maybe the actual <select> is:

<select name="AllStudents" ...>
No big deal. Just change my first line to

var students = document.NameOfThatForm.AllStudents;

Actually, naming of <form>s is deprectated in XHTML, so you might find that the <form> has an ID instead of (or in addition to?) a name. Maybe:

<form id="MainForm">
<select name="AllStudents">

So, again:

var form = document.getElementById("MainForm");
var students = form.AllStudents;
var selected = students.options[students.selectedIndex].value;


If you showed us the actual HTML of the <form> and <select>, we could help better.

Dec 17th, 2009, 07:37 PM
Thanks. I sorted it. We probably posted at the same time :)

Old Pedant
Dec 17th, 2009, 07:38 PM
Okay, that works if you put an id on the <select>. Generally, I argue *against* doing that.

Reason: If the <form> is sent to another page (either via method="get" or method="post") then *ONLY* fields with names are sent along. The id of a field is completely ignored for form submission purposes.

If you get in the habit of using id's for form fields and forget to use a name, then that field doesn't get sent.

Of course, sometimes that's actually what you want: An easy way to have form fields that are only used in the construction of the information to be sent to the next page.

Generally, though, you want to use field names. And then the way to refer to them is via

or, as I showed,