Getting the text from a HTML select drop down box using Javascript

18 03 2009

I have a web page that uses an HTML select drop down list:

<select name="Company"> <%GetCompanies();%> </select>

When this web page is submitted, I need to show a Javascript ‘confirm’ box that would ensure that the user was sending the document created by the web page to the correct company. In order to do this, I needed to retrieve the selected company name from the select drop down list.

There are 3 pieces of information that you could get from this drop down list. The index (0,1,2 etc) which depends on which option is selected in the drop down list. The value, which in my case was a CompanyId that is retrieved from the database via my ‘GetCompanies()’ method, and the text, which is the actual text that is being displayed in the selected item of the drop down list. I placed the following code on the submit button:

<input type="submit" value="Send" onclick="return confirmSubmit()" />

The ‘confirmSubmit()’ is a Javascript function declared at the top of my page as follows:

function confirmSubmit()
var companyIndex = document.invoice.OrgID.selectedIndex;
var companyName = document.invoice.OrgID[companyIndex].text;
var ok = confirm('Are you sure you want to send this invoice to ' + companyName + '?');
return true;
return false;

So I get the selectedIndex, and use that value to find the text. If you didn’t do it that way, you would get returned ‘undefined’. Another way to find it would be:


As opposed to:


If true (Ok) is returned, the button continues to submit as expected. If false (Cancel) is returned, nothing happens and the user is free to change any details on the page.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: