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 + '?');
if(ok)
return true;
else
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:
document.getElementByName('OrgID').selectedIndex
As opposed to:
document.invoice.OrgID.selectedIndex
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.