Reputation: 3
Some context for my task - users see a table and select rows to then be uploaded via sql to the main sql table.
My question - I need to be able to only load the selected rows in my table to an array.
Right now I can only load the whole table to an array in Javascript and then post it to the php page and then print_r the array and I get all the values with this piece of code:
echo '<script>
var myTableArray = [];
$("#uploads_approval tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find("td");
if (tableData.length > 0) {
tableData.each(function() {
arrayOfThisRow.push($(this).text());
});
myTableArray.push(arrayOfThisRow);
}
});
var selectedRows = document.getElementById("selectedRows");
selectedRows.value = myTableArray;
</script>';
I have tried multiple things to only get the selected rows such as changing this line from:
$("#uploads_approval tr").each(function() {
to this:
$("#uploads_approval tr.selected").each(function() {
but then my array output returns nothing.
I have also tried something like this but also no success
echo "<script>
var Array2 = [];
$('#uploads_approval tr').each(function() {
var tableData = $(this).find('td');
for(i = 0; i < tableData.length; i++){
tableData.each(function() {
var thisRow =
document.getElementByClassName('selected').Text();
array2.push(thisRow);
});
}
var selectedRows = document.getElementById('selectedRows');
selectedRows.value = Array2;
}
</script>";
Click event for selecting rows:
echo "<script> $('#uploads_approval tr').click(function(){ $(this).toggleClass('selected'); }); </script>";
Form for Submit event:
echo '<form action="uploads_approval.php" method="post" >' . '<input
type="hidden" name="uploadRows" id="uploadRows" value="1" /> '; echo
'<button id="button" ">SELECT</button> '; echo '<input type="hidden"
name="selectedRows" id="selectedRows" value="1" /> '; echo '</form>';
I am very new to Javascript/Jquery so I am learning as I go.
Any help or advice regarding this would be appreciated.
Upvotes: 0
Views: 1677
Reputation: 32354
update your values each time you click the tr
$('#uploads_approval tr').click(function(){
$(this).toggleClass('selected');
var row = [];
$('.selected').each(function(i,v){
row.push($(v).text());
});
$('#selectedRows').val(row);
});
$('#uploads_approval tr').click(function() {
$(this).toggleClass('selected');
var row = [];
$('.selected').each(function(i, v) {
row.push($(v).text());
})
$('#selectedRows').val(row);
});
.selected {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<table id="uploads_approval">
<tbody>
<tr>
<td>tr1</td>
</tr>
<tr>
<td>tr2</td>
</tr>
<tr>
<td>tr3</td>
</tr>
<tr>
<td>tr4</td>
</tr>
</tbody>
</table>
<input type="text" id="selectedRows">
Upvotes: 1