Deeds
Deeds

Reputation: 125

Passing selected value of dropdownlist in URL

I have a dropdownlist that opens a new window when I select an item from the list. How can I pass a dropdownlist value to the new window in a URL?

My code looks like this:

<asp:DropDownList ID="ddlAdd" runat="server" CssClass="ddl" OnChange="javascript:openWindow('add.aspx?ddlAddValue=', 800, 885)">
    <asp:ListItem>One</asp:ListItem>
    <asp:ListItem>Two</asp:ListItem>
    <asp:ListItem>Three</asp:ListItem>
</asp:DropDownList>

This is the JavaScript function:

function openWindow(url, windowHeight, windowWidth)
{
    var centerHeight = (screen.height - windowHeight) / 2;
    var centerWidth = (screen.width - windowWidth) / 2;
    var features = "height=" + windowHeight + ", width=" + windowWidth + ", top=" + centerHeight + ", left=" + centerWidth + ", scrollbars=" + 1;
    var popUp = window.open(url, "", features);
}

Upvotes: 4

Views: 2584

Answers (2)

Derek Hunziker
Derek Hunziker

Reputation: 13141

You can simply refer to this.value to get the value of the underlying select.

OnChange="javascript:openWindow('add.aspx?ddlAddValue=' + escape(this.value), 800, 885)"

Also, this is easily handled in jQuery, if that's how you roll:

$(function(){

  $('select[id$=ddlAdd]').change(function () {

      var addValue = $(this).val();

      if (addValue) { 
          // window opening logic here
      }

      return false;
  });
});

Upvotes: 4

freefaller
freefaller

Reputation: 19953

You can pass the dropdown object directly into the javascript like this...

onchange="openWindow('add.aspx?ddlAddValue=', 800, 885, this)"

(Note, you do not need the javascript: prefix in an onchange command - the browser already knows it's javascript)

And then in your function...

function openWindow(url, windowHeight, windowWidth, dd)
{
   url = url + encodeURIComponent(dd.options[dd.selectedIndex].value);
   ...

Upvotes: 1

Related Questions