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 + '?');
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.

Advertisements




Are you sure you want to do that? Pop-up boxes with ASP.net web applications.

29 01 2009

My current project required that when a user tried to delete something, they would get a warning, that deleting that would delete other things to and offer them the option to proceed or cancel. There are many ways to do this, the best way I found to do it was using the following code:

Response.Write("<script>var result=confirm('Are you sure you want to delete this project? Doing so will also delete all units and tests associated to this project. Click OK to proceed, or Cancel to return to the Project Maintenance screen.');if(result){window.document.location.href='SubmitProject.aspx';}else{window.document.location.href='ProjectMaintenance.aspx';}</script>");

So the Javascript function says:

show the confirmation box
if(result == 'Ok')
{
go to SubmitProject.aspx
}else{
return to current page ProjectMaintenance.aspx
}

This is a very hand bit of code that I will probably use quite a lot from now on!