2011-12-07 37 views
0

我在for循環中有一個下拉菜單。我在這個循環中也有一個下載pdf按鈕。我希望能夠點擊此下載pdf按鈕,然後在javascript中選擇下拉列表中的選定值,然後最終運行一個函數並找到與所選值相關的正確pfd位置。如何選擇父級下拉選中的值

編輯:

<table> 
    <tr> 
     <td></td> 
     <td> 
     @Html.DropDownList("Dropdown", Model.Dropdowns[i], new { id = Model.Industry[i].Id, @class = "dropdown"}) 
    </td> 
    </tr> 
    <tr> 
     <td></td> 
     <td> 
      <a href="#" class="DownloadPDF"> Download PDF</a>             
     </td> 

<script type="text/javascript"> 
$(document).ready(function() { 

    $(".DownloadPDF").click(
     function() { 
      var selected = $(this).parent().find(".dropdown option:selected").val(); 
      alert(selected); 
     } 
    ); 
}); 

這個代碼僅返回警告說未定義

回答

1

這是更好地訂閱change事件你的下拉列表:

$(document).ready(function() { 
    $('select.dropdown').change(function() { 
     var $tr = $(this).closest('tr'); 
     var $btn = $tr.next().find('a.DownloadPDF'); 
     $btn.attr('href', 'mydownloadhandler?pdf' + $(this).find('option:selected').val()); 
    }); 
}); 

代碼:http://jsfiddle.net/b4Dxv/1/

無論如何,如果我們將從按鈕啓動:

$(document).ready(function() { 
    $(".DownloadPDF").click(function() { 
      var selected = $(this).closest('tr').prev().find(".dropdown option:selected").val(); 
      alert(selected); 
     } 
    ); 
}); 
+0

我仍然得到未定義的錯誤,我會給你的第一個例子 – Beginner

+0

我設置了錯誤的屬性'src'而不是'href'。我已經添加了工作示例 – Samich

0

也許沒有父:

var selected = $(".dropdown option:selected", $(this).parent()).val(); 
+0

這是行不通的,但它選擇第一個下拉的值。我想要下拉按鈕上方的值。 – Beginner

+0

例如可能有三個下拉菜單和三個按鈕,因爲這是一個循環 – Beginner

+0

我添加了$(this).parent()作爲select的基礎。也許你需要$(this).parent()。parent()。 – PiTheNumber

0

我把它的下拉列表,並在不同的表格單元格鏈接的,但在同一行?

你在這裏做什麼只檢查鏈接的父母。鏈接的父級是td元素。你需要找到的是父母tr元素。試試這個:

var selected = $(this).closest('tr').find(".dropdown option:selected").val();