开发者

Finding all checked check boxes isnt working

I've tried a few different ways of finding all the checkboxes that are checked but I don't know why this one isn't working.

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);
}

and the HTML/ERB:

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

<fieldset style="width: 400px;">
    <legend>Current Projects</legend>
    &开发者_JS百科lt;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>

Not sure why this isn't working but maybe someone can see what I can't.


The parameter to .each need to be in round brackets .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;
    });
}


The other answer already told you about your problem, but your code can be improved. There is no need to use a loop counter, each provides the iteration number.

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

You do not even need the index when you have methods on the array to add element

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜