jeudi 25 juin 2015

Return an array of all checkboxes checked upon click

I've got a table with a checkbox in each row, like this:

<table id='users'>
    <thead>
    ...
    </thead>
    <tbody>
        <tr>
            <td><input type='checkbox' name='users' id='someUserId'></td>
            <td> some variable pid </td>
            <td>...</td>
        </tr>
        <tr>
            <td><input type='checkbox' name='users' id='someOtherId'></td>
            <td> some other variable pid </td>
            <td>...</td>
        </tr>
        ...
    </tbody>
</table>

Now i want to put the text of the columns next to the checkboxes, the pids, into an array, then pass the array to a function. The function should take each record in the array and process them.

My best try so far:

function myFunction(arr[]){...}

function getIds(obj){
var $table = $("#users");
alert($table.attr("id"));
var $cboxes = $table.find("input:checkbox").toArray();
alert($cboxes);

var checkedArray = [];
var pid;
for(i = 0;i < $cboxes.length; i++){
    if($cboxes[i].checked){
        pid = $cboxes.parent().siblings().eq(0).text();
        checkedArray.push(pid);
        alert(pid);
    }
}
alert(checkedArray);
return checkedArray;
}

$("#button").click(function(){
    var ids = getIds();

    for(i = 0; i < ids.length; i++){
        myFunction(ids[i]);
        alert("Function executed for "+ids[i]+".");
    }
});




Aucun commentaire:

Enregistrer un commentaire