2011-09-15 40 views
0

我已經嘗試了幾種不同的方法來查找所有已選中的複選框,但我不知道爲什麼這一個不起作用。找到所有選中的複選框不能正常工作

的JavaScript:

var idList = new Array(); 
function getIds() 
{ 
    var loopCounter = 0; 
    // find all the checked checkboxes 
    $('input[name^="check_"]:checked').each 
    { 
     function() 
     { 
      //fill the array with the values 
      idList[loopCounter] = $(this).val(); 
      loopCounter += 1; 
     } 
    }; 
} 
function showArray() 
{ 
    alert(idList); 
} 

和HTML/ERB:

<% user_project_ids = @users_projects.collect { |up| up.project_id } %> 

<fieldset style="width: 400px;"> 
    <legend>Current Projects</legend> 
    <table> 
     <tr> 
      <th>Project ID</th> 
      <th>Project Name</th> 
     </tr> 
     <% @projects.each do |project| %> 
     <tr> 
      <td><%= project.id %></td> 
      <td><%= project.project_number %></td> 
      <td><%= project.project_name%></td> 
      <td><input name="check_<%= project.id %>" type="checkbox" 
       <%=' checked="yes"' if user_project_ids.include? project.id %>></td> 
     </tr> 
     <% end %> 
    </table> 
</fieldset> 

<div onclick="getIds();"> 
    CLICK 
</div> 

<button onclick="showArray()">Click Again</button> 

不知道爲什麼,這是行不通的,但也許有人可以看到我不能。

回答

2

的參數。每次需要在圓括號.each()

function getIds() 
{ 
    var loopCounter = 0; 
    // find all the checked checkboxes 
    $('input[name^="check_"]:checked').each(function() { 
     //fill the array with the values 
     idList[loopCounter] = $(this).val(); 
     loopCounter += 1; 
    }); 
} 
0

對方回答已經告訴你關於你的問題,但你的代碼可以得到改善。不需要使用循環計數器,每個計數器都提供迭代次數。

function getIds() 
{ 
    //reset idArray 
    idList = []; 
    // find all the checked checkboxes 
    $('input[name^="check_"]:checked').each(function(ind) { 
     idList[ind] = $(this).val(); 
    }); 
} 

你甚至都不需要索引時,你有數組方法來添加元素

function getIds() 
{ 
    //reset idArray 
    idList = []; 
    // find all the checked checkboxes 
    $('input[name^="check_"]:checked').each(function() { 
     idList.push($(this).val()); 
    }); 
} 
+0

感謝諮詢花花公子,已經做了類似的東西在時間後,我得到了答案。 – SD1990