Get the unique total scores of students - javascript

I have a form on my school web application where teachers are able to add scores for students and at the end of each row, the total, which is the sum of input values is automatically calculated per student.
The problem is that it output the total of all the students instead of the total of individual students on all the rows even ones with no scores added.
How do I get the unique total value for each row?
Below is my code
<?php if($class_id >= 1 && $class_id <= 4 && $student['is_secmid'] == 1){?>
<form method="post" action="<?php echo site_url('admin/examgroup/entrymarks') ?>" id="assign_form1111">
<input type="hidden" id="max_mark" value="<?php echo $subject_detail->max_marks; ?>">
<?php
if (isset($resultlist) && !empty($resultlist)) {
?>
<div class="row">
<div class="col-md-12">
<input type="hidden" name="exam_group_class_batch_exam_subject_id" value="<?php echo $exam_group_class_batch_exam_subject_id; ?>">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>C.A 1 (10.0)</th>
<th>C.A 2 (10.0)</th>
</tr>
</thead>
<tbody>
<?php if (empty($resultlist)) {
?>
<tr>
<td colspan="7" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td>
</tr>
<?php
} else {
foreach ($resultlist as $student) {
?>
<tr class="std_adm_<?php echo $student['admission_no']; ?>">
<input type="hidden" name="prev_id[<?php echo $student['exam_group_class_batch_exam_students_id'] ?>]" value="<?php echo $student['exam_group_exam_result_id'] ?>">
<input type="hidden" name="exam_group_student_id[]" value="<?php echo $student['exam_group_class_batch_exam_students_id'] ?>">
<td><?php echo $student['admission_no']; ?></td>
<td style="white-space: nowrap;"><?php echo $student['lastname'] . " " . $student['firstname']; ?></td>
<td> <input type="number" class="marksssss2 form-control" min="0" max="10" name="exam_group_student_ca1_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_get_ca1']; ?>" step="any"></td>
<td> <input type="number" class="marksssss3 form-control" min="0" max="10" name="exam_group_student_ca2_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_get_ca2']; ?>" step="any"></td>
<td> <output class="result"></output></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<?php if ($this->rbac->hasPrivilege('exam_marks', 'can_edit')) { ?>
<button type="submit" class="allot-fees btn btn-primary btn-sm pull-right" id="load" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Please Wait.."><?php echo $this->lang->line('save'); ?>
</button>
<?php } ?>
</div>
</div>
<?php } ?>
<script>
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
var parent = $(this).closest('.row');
parent.find('input[type="number"]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
parent.find('.result').html(total);
});
</script>

you missed class row on <tr> and you are trying to find it on closest div from javascript, and you are getting this (<div class="row">), it have all the (<input type="number").
you forget to add class to TR. Add class row on <tr> so you can get all (<input type="number") inside the tr.
because of not added class on TR you are facing issue that all total have same numbers.

Related

Changing background color onclick on a specific table row

I want to change the background color of a specific clicked table row. It also should change it back to the original color. Back and forth from red to green. And it should also check the checkbox. Green = checkbox checked/ Red = checkbox unchecked.
The rows look like this
<tr id="<?php echo $row['id'] ?>" value="<?php echo $row['id'] ?>">
and for JQUERY I have this:
$(document).ready(function() {
$('.table tr').click(function(event) {
var id = $(this).attr('id');
var bcolor = $('.task').css('background-color');
console.log(id);
console.log(bcolor);
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
if (bcolor == 'rgb(205, 92, 92)') {
$('.task').css('background-color', 'green');
} else {
$('.task').css('background-color', 'indianred');
}
};
});
});
How can I use the var id = $(this).attr('id'); to change the background color only for the specific clicked row?
Right now it makes every row green by clicking on any of them.
Whole main.php:
Header
<?php include 'taskpdo.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>To Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>
</head>
Body
<body>
<!-- CONFIRM MESSAGE -->
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif?>
<div class="spacer">
<!-- Heading -->
<div class="heading">
<h2>To Do List</h2>
</div>
<!-- Userinformation -->
<div class="logout">
<?php if (isset($_SESSION['username'])): ?>
<p>Welcome<strong><?php echo $_SESSION['username']; ?></strong></p>
<p>logout</p>
<?php endif?>
</div>
</div>
Table
<table class="table">
<thead>
<tr>
<th>Check</th>
<th>UID</th>
<th>Username</th>
<th>Num</th>
<th>Tasks</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$tasks = sqlsrv_query($db,
"SELECT * FROM todo
join registrieren
on username = ersteller
where username = '" . $_SESSION['username'] . "'");
Rows
$i = 1;
while ($zeile = sqlsrv_fetch_array($tasks)) {
?>
<tr id="<?php echo $zeile['id'] ?>" type="checkbox" name="check[]" value="<?php echo $zeile['id'] ?>">
<td class="task"><input type="checkbox" id="check--<?php echo $zeile['id'] ?>"></td>
<input type="hidden" name="id" value="<?php echo $zeile['id']; ?>">
<td class="task" ><?php echo $zeile['uid'] ?></td>
<td class="task" ><?php echo $zeile['username'] ?></td>
<td class="task" ><?php echo $zeile['id'] ?></td>
<td class="task" id="<?php echo $zeile['id'] ?>" ><?php echo $zeile['task'] ?></td>
<td class="task" onclick="myFunction(<?php echo $zeile['id'] ?>)">
<form method="post" action="main.php">
<button type="submit" name="edit">
Edit
</button>
<input type="hidden" name="id" value="<?php echo $zeile['id']; ?>">
<input type="hidden" name="task" value="<?php echo $zeile['task']; ?>">
</form>
</td>
<td class="task" onclick="myFunction(<?php echo $zeile['id'] ?>)">
<form method="post" action="main.php" >
<button type="submit" name="delete">
Delete
</button>
<input type="hidden" name="id" value="<?php echo $zeile['id']; ?>">
</form>
</td>
</tr>
<?php
$i++;}
?>
</tbody>
</table>
Buttons
<form method="post" action="main.php" class="input_form">
<input type="hidden" name="ersteller" value="<?php echo $_SESSION['username']; ?>">
<?php
if ($update == true): ?>
<input type="text" name="task" class="task_input" value="<?php echo $task ?>">
<button type="submit" name="update" id="add_btn" class="add_btn">Update</button>
<input type="text" name="id" value="<?php echo $id ?>">
<?php else: ?>
<input type="text" name="task" class="task_input">
<button type="submit" name="addtask" id="add_btn" class="add_btn">Add Task</button>
<input type="hidden" name="id" value="<?php echo $id ?>">
<?php endif ?>
</form>
</body>
</html>
You can use toggleClass of jQuery:
// css for put in your element
.common-class {
background-color: #ff0000; // replace for your color
}
.highlight-class {
background-color: #0000ff !important; // replace for your color
}
$('your-selector').toggleClass('highlight-class'); // jQuery
Bensilson's answer helped me and i want to clarify what i have done:
I delete the class='task'inside the <td> and put it into the <tr> - Tag.
I've done a .highlighttask{background-color: green !important} inside the css.
And inside the js i've done
$(document).ready(function() {
$(".table tr").on('click', function() {
var checked = $(this).find('input[type="checkbox"]');
checked.prop('checked', !checked.is(':checked'));
$(this).toggleClass('highlighttask');
});
});
Now it overrights the background-color on a specific row AND it checks the checkbox of the specific row.
Thanks!

Clicking on any radio button in my created list results in only the first <select> field being activated

Here is the video in specific from what i mean. It is hosted on my personal drive
video
Here is my code
<?php
$pagetitle="Search Report";
include "includes/header.php";
include("config.php");
include("connection.php");
error_reporting(E_ALL ^ E_DEPRECATED);
$name=$_GET['filo'];
$ksm=$_GET['kisim'];
$drs=$_GET['hders'];
$ndrs=$_GET['dname'];
$tch=$_GET['tname'];
?>
<script>
//Here Is javascript code
function enable() {
document.getElementById('option').disabled=false;
}
</script>
<style type="text/css">
input[type="radio"]{
margin: 0px 4px 0px;
}
</style>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange"> </span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<div class="table-responsive">
<table class="ui celled table table table-hover">
<form action="check.php" method="get">
<thead>
<tr>
<th>Adı ve Soyadı</th>
<th>Dersin Adı</th>
<th>Dersin Saatı</th>
<th>Öğretim Elemanı</th>
<th>Durum</th>
<th>Sebepi</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<?php
$query3=mysqli_query($connect,"select * from student where filo='$name' and kisim='$ksm' ORDER BY student_name");
$arra=-1;
while($row=mysqli_fetch_row($query3))
{
$arra++;
?>
<tr>
<td><?php echo $row[1] ?></td>
<input type="hidden" value="<?php echo $row[1] ?>" name="std_name[]">
<td><?php echo $ndrs ?></td>
<input type="hidden" value="<?php echo $ndrs ?>" name="ndrs[]">
<td><?php echo $drs ?></td>
<input type="hidden" value="<?php echo $drs?>" name="drs[]">
<td><?php echo $tch ?></td>
<input type="hidden" value="<?php echo $tch ?>" name="tch[]">
<td>
///////HERE IS ONE PART OF THE CODE
<input type="radio" name="attendance[<?php echo "$arra" ?>]" value="Mevcut" checked="checked" >Mevcut
<input type="radio" name="attendance[<?php echo "$arra" ?>]" onclick="enable()" value="Gayri">Gayrı
</td>
<td>
<select class="form-control" id="option" name="option[<?php echo "$arra" ?>]" disabled >
<option selected value="Mevcut">Mevcut</option>
<option value="Vizite">Vizite</option>
<option value="Hst Muayene">Hst Muayene</option>
<option value="Izinli">Izinli</option>
</select>
</td>
<td><?php echo $row[0] ?>
<input type="hidden" value="<?php echo $row[0] ?>" name="id[]">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<button type="submit" class="btn btn-success btn-lg btn-block" name="submit2">Gönder</button>
</form>
</div><!--table-responsive-->
</div><!--row-->
</div><!--container-->
<?php include "includes/footer.php"; ?>
I try to explain my problem.
Scenario is like that. Some infos are taken from a submit form and with this infos i create a list then created list has 2 radio buttons and by default a disabled select area.
The problem is here. When i click on "Gayri" button field must be activated for every person in that list instead of that just the first field is activated.
Can anyone help me? I want for every possible person in the list when i click on "gayri" radio button the field to be activated.

File Handling POST Data not being passed

So I'm trying to do Ajax POST in my wordpress site which is used in checking if checkboxes are checked and getting their values to get updated on the database on click. Using the usual PHP form submit is the easiest but the fields that I'm trying to get is outside the form.
After button click, I created an alert if the data that I need is being picked up (and they are) so I can continue with the Ajax POST. However, the POST data is not showing when I inserted an alert on the second file.
Here's my code (content-orders.php):
<div class="container">
<div class="row">
<div class="col-sm-6 text-left">
<form class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="BA">Bulk Actions</option>
<option value="MTT">Move To Trash</option>
<option value="MP">Mark Processing</option>
<option value="MOH">Mark On-Hold</option>
<option value="MC">Mark Complete</option>
</select>
<button class="btn btn-success" type="submit" id="check-all">Filter</button>
</form>
</div>
<div class="col-sm-6 text-right">
<form class="form-inline" method="get">
<?php $statuses = wc_get_order_statuses(); ?>
<select name="orderstatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
<option value="any">-- Select Status --</option>
<?php foreach( $statuses as $skey => $status ) : ?>
<option <?php echo ( ( isset( $_GET['orderstatus'] ) && $_GET['orderstatus'] == $skey ) ? 'selected="selected"' : '' )?> value="<?php echo $skey;?>"><?php echo $status;?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Filter" />
</form>
</div>
</div>
<?php
$status_query = 'any';
if(isset( $_GET['orderstatus'] )) {
$status_query = $_GET['orderstatus'];
}
$filters = array(
'post_status' => $status_query,
'post_type' => 'shop_order',
'posts_per_page' => 200,
'paged' => 1,
'orderby' =>'modified',
'order' => 'DESC'
);
$loop = new WP_Query( $filters );
?>
<div class="row">
<div class="table-responsive">
<table class="table responstable table-striped">
<thead>
<tr>
<th><input id="checkAll" type="checkbox"></th>
<th>Order</th>
<th>Purchased</th>
<th>SKU</th>
<th>Ship To</th>
<th>Date</th>
<th>Total</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
if( !($loop->have_posts())) {
?>
<tr>
<td colspan="8" class="text-center">No data.</td>
</tr>
<?php
} else {
while ( $loop->have_posts() ) {
$loop->the_post();
$order = new WC_Order($loop->post->ID);
?>
<tr>
<td><input id="select-item" name="bulk_actions_check" type="checkbox" value="<?php echo $loop->post->ID; ?>"></td>
<td><?php echo $order->billing_first_name." ".$order->billing_last_name; ?></td>
<td>
<?php
foreach ($order->get_items() as $key => $lineItem) {
echo $lineItem['qty']." ".$lineItem['name']."<br />";
}
?>
</td>
<td><?php
foreach ($order->get_items() as $key => $SKUItem) {
$sku_handler = new WC_Product($SKUItem['product_id']);
echo $sku_handler->sku."<br />";
}
?></td>
<td><?php echo $order->get_shipping_address(); ?></td>
<td><?php explode(" ",$order->order_date); echo $order->order_date[0];?></td>
<td><?php echo "$".$order->get_total(); ?></td>
<td><?php echo $order->status; ?></td>
<td>
<form class="form-inline" method="get">
<input type="hidden" name="status_id" value="<?php echo $order->id; ?>" />
<?php if ($order->status != 'cancelled' && $order->status != 'completed') { ?>
<?php if ($order->status != 'processing') { ?>
<button class="btn btn-primary" id="processing-<?php echo $order->id; ?>" type="submit" name="update_status" value="processing"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-success" id="complete-<?php echo $order->id; ?>" type="submit" name="update_status" value="completed"><i class="fa fa-check" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-info" id="view-<?php echo $order->id; ?>" type="submit" name="update_status" value="view"><i class="fa fa-eye" aria-hidden="true"></i></button>
</form>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#checkAll").click(function () {
jQuery('input:checkbox').not(this).prop('checked', this.checked);
});
jQuery('#check-all').click(function(){
var bulk_action_status = jQuery('#bulk_action_stat').val();
var checkValues = jQuery('input[name=bulk_actions_check]:checked').map(function()
{
return jQuery(this).val();
}).get();
alert(checkValues);
jQuery.ajax({
url: '<?php echo get_stylesheet_directory_uri(); ?>/test.php',
type: 'post',
data: { ids: checkValues },
success:function(data){
}
});
});
});
On test.php is just
print_r($_POST);
These 2 files are in my child theme.
I hope someone can help. Thanks!
-Eli
I'm a bellend.
The form should just have an ID and add the form ID to all the fields outside the form.
<form id="bulk_action_filter" class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="">Bulk Actions</option>
<option value="trash">Move To Trash</option>
<option value="processing">Mark Processing</option>
<option value="on-hold">Mark On-Hold</option>
<option value="completed">Mark Complete</option>
</select>
<input form="bulk_action_filter" type="submit" name="filter_bulk_actions" id="check-all" value="Apply"/>
</form>
<input form="bulk_action_filter" id="select-item" name="bulk_actions_check[]" type="checkbox" value="<?php echo $loop->post->ID; ?>">

PHP Looping Javascript Just Show The First Record

I have a view code:
<?php
$i = 1;
//var_dump($this->productList);
foreach ($this->productList as $data) {
$desc=explode(",",$data['descriptions']);
?>
<tr>
<th colspan="3">
<input type="hidden" id="id_pack" name="id_pack" value="<?php echo $data['package_id']; ?>">
<input type="hidden" id="nama_pack" name="nama_pack" value="<?php echo $data['package_name']; ?>">
<h4 align="center" class="title-pack"><?php echo $data['package_name']; ?></h4>
</th>
</tr>
<tr id="dashe">
<td>
<ul class="myul">
<?php foreach($desc as $descriptions) { ?>
<li class="myli"> <?php echo $descriptions; ?></li>
<?php } ?>
</ul>
</td>
<td>
<h4 class="prize">
Rp. <?php echo number_format($data['price'],2);?>
/ month
</h4>
</td>
<td>
<p id="order" name="order" class="mybutton" data-toggle="modal" data-target=".mymodal">Order</p>
</td>
</tr>
<?php
$i++;
}
?>
And this the javascript:
document.getElementById("order").addEventListener("click", tampilkanHrm);
function tampilkanHrm() {
var pilihan=$("#nama_pack").val();
document.getElementById("choice").innerHTML = pilihan;
document.getElementById("pack").value = pilihan+" Package";
}
the problem is, in the order button it always show the same record. Just show the first data, even i clicked other order button. Hope somebody help.
You can't assign same id for multiple elements.
So, have different ids.
<?php
$i = 1;
//var_dump($this->productList);
foreach ($this->productList as $data) {
$desc=explode(",",$data['descriptions']);
?>
<tr>
<th colspan="3">
<input type="hidden" id="id_pack<?php echo $i ?>" name="id_pack" value="<?php echo $data['package_id']; ?>">
<input type="hidden" id="nama_pack<?php echo $i ?>" name="nama_pack" value="<?php echo $data['package_name']; ?>">
<h4 align="center" class="title-pack"><?php echo $data['package_name']; ?></h4>
</th>
</tr>
Similarly create buttons with different ids.
<td>
<p id="<?php echo $i ?>" name="order" class="mybutton" data-toggle="modal" data-target=".mymodal">Order</p>
</td>
Then change your javascript to jquery. Hope, you might also be using jquery [ understood from your code ]
$(".mybutton").on("click", function() {
var identifier = $(this).attr("id");
var pilihan=$("#nama_pack"+identifier).val();
$("#choice").html(pilihan);
});
Change your code like this and check.

Datatables child row with PHP data from Codeigniter

I have a datatable that is displaying 6 total columns of data from my database. The 7th column is a "+" button that expands down and displays a further 7 pieces of data about that specific entry. I am also using Codeigniter for my framework. Originally I was using colspan to make the row hidden and squeeze down, and found out that was a no-no, so I looked into Datatables child rows here: https://datatables.net/examples/api/row_details.html but it appears that the data needs to be there after the generation of the table.
I have the HTML/PHP to generate the table and populate it with data now. The data is sent from my model to controller and to this view:
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover" id="dataTables-listlg">
<thead>
<th>ItemID</th>
<th>Name</th>
<th>Quantity</th>
<th>Identified?</th>
<th>Item Type</th>
<th>Unique ID</th>
<th>Details</th>
</thead>
<tbody>
<?php foreach ($storage_items as $storageItem) { ?>
<tr>
<td><?php echo $storageItem['nameid']; ?></td>
<td><?php echo $storageItem['name']; ?></td>
<td><?php echo $storageItem['amount']; ?></td>
<td><?php echo $storageItem['identify']; ?></td>
<td><?php echo $item_types[$storageItem['type']]; ?></td>
<td><?php echo $storageItem['unique_id']; ?></td>
<td><center><a data-toggle="collapse" data-parent="#accordion" href="#storagedetails<?php echo $storageItem['id']; ?>"><button type="button" class="btn btn-primary btn-circle btn-sm"><i class="fa fa-plus"></i></button></a></center></td>
<td>
<?php echo form_open('/account/edititem', array('class' => 'form-inline'), array('id' => $storageItem['id'], 'item_loc' => "inventory", 'acctid' => $acct_data->account_id)); ?>
</td>
</tr>
<tr>
<td colspan="8" class="hiddenRow">
<div id="storagedetails<?php echo $storageItem['id']; ?>" class="panel-collapse collapse">
<div class="panel-body">
<div class="row">
<div class="col-xs-2">
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem['refine']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> />
</div>
<div class="col-xs-2">
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem['attribute'] == 1) { echo "checked"; } if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "disabled"; } ?> />
</div>
<div class="col-xs-2">
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem['bound'] == 1) { echo "checked"; } ?> />
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem['card0']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem['card1']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem['card2']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem['card3']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
The javascript I'm using now to make the table is:
<script>
$(document).ready(function() {
$('#dataTables-listlg').DataTable({
"responsive": true,
"lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
"searching": false,
"defaultContent": "",
});
});
</script>
Where the <td colspan="8" class="hiddenRow"> is, is where I want to make the child row drop down (UNDER the entry showing the additional information). I've seen the example but I have no idea how to get my data into the proper format to put it into the datatable and where it should go. Here is the controller with the relevant part:
$data['storage_items'] = $this->accountmodel->get_storage_items($aid);
$this->load->view('account/details',$data);
$this->load->view('footer'); // Where the javascript is above
And the model:
function get_storage_items($aid) {
$this->db->select('*');
$this->db->from('storage')->order_by('storage.id', 'asc');
$this->db->where('storage.account_id', $aid); // This is just sorting out the results from that specific account
$q = $this->db->get();
return $q->result_array();
}
It looks like I need to get my array of results from my model into json/ajax but have no idea how I'd get this all the way to my footer AFTER the table is generated. Any help you can provide would be appreciated.
---Edit---
After looking over the answer below and mulling over thoughts, I have changed things to the following. Here is the complete view from foreach loop to the end, including the Javascript to put stuff in the 'content' array:
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover display" id="dataTables-listlg">
<thead>
<th>ItemID</th>
<th>Name</th>
<th>Quantity</th>
<th>Identified?</th>
<th>Item Type</th>
<th>Unique ID</th>
<th>Details</th>
<th>Options</th>
</thead>
<tbody>
<?php foreach ($storage_items as $storageItem) { ?>
<tr>
<td><?php echo $storageItem['nameid']; ?></td>
<td><?php echo $storageItem['name']; ?></td>
<td><?php echo $storageItem['amount']; ?></td>
<td><?php echo $storageItem['identify']; ?></td>
<td><?php echo $item_types[$storageItem['type']]; ?></td>
<td><?php echo $storageItem['unique_id']; ?></td>
<td class="details-control"></td>
<td>
<button type="submit" class="btn btn-success btn-sm <?php if ($check_perm['editstorageitem'] == 0) { echo "disabled"; } ?>" >Edit</button>
<button type="button" class="btn btn-danger btn-sm <?php if ($check_perm['editstorageitem'] == 0) { echo "disabled"; } ?>">Delete</button>
</td>
</tr>
<script>
var content = [];
content[<?php echo $storageItem["id"]; ?>] = '"'<?php echo form_open("/account/edititem", array("class" => "form-inline"), array("id" => $storageItem["id"], "item_loc" => "inventory", "acctid" => $acct_data->account_id)); ?> \
<div class="panel-body"> \
<div class="row"> \
<div class="col-xs-2"> \
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem["refine"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /> \
</div> \
<div class="col-xs-2"> \
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem["attribute"] == 1) { echo "checked"; } if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "disabled"; } ?> /> \
</div> \
<div class="col-xs-2"> \
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem["bound"] == 1) { echo "checked"; } ?> /> \
</div> \
</div> \
<br /> \
<div class="row"> \
<div class="col-xs-2"> \
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem["card0"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem["card1"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem["card2"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
'<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem["card3"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
</div> \
<?php echo form_close(); ?> \
</div>'"';
</script>
<tr item_id="<?php echo $storageItem['id']; ?>">
</tr>
<?php } ?>
</tbody>
</table>
</div>
and my javascript in the footer looks like this now:
<script>
$(document).ready(function() {
var table = $('#dataTables-listlg').DataTable({
"responsive": true,
"lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
"searching": false,
"defaultContent": "",
});
// Add event listener for opening and closing details
$('#dataTables-listlg tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(content[tr.attr('item_id')]).show();
tr.addClass('shown');
}
});
});
</script>
In fact, the 'unique_id' in this table is not as "unique" as I thought (I didn't design it, just writing the backend for it). There is however a unique key on the table 'id', so that's what I'm using to make sure I get the right value.
This however is not working. I am getting an error in the console:
SyntaxError: missing ; before statement - appears on the line that starts content[<?php echo $storageItem["id"]; ?>] =... in each iteration of the foreach
I'm also getting the error from the webpage warning about DataTables: DataTables warning: table id=dataTables-listlg - Requested unknown parameter '0' for row 1. For more information about this error, please see http://datatables.net/tn/4
Additionally, the child row doesn't drop down. Did I misunderstand or make a silly mistake?
dataTables child rows dynamically injects a row on the form
<tr colspan="number of columns">
<td>
... user content ...
</td>
</tr>
user content is passed to the injected row upon the call (from the example) :
row.child(<user content>).show();
You cannot use hidden rows as a base for child rows. I would suggest you collect all the content you output to hidden rows in the loop into a javascript array :
var content = [];
content[<? echo $storageItem['unique_id']; ?>] = '"'+<? echo form_open(...) + everything from your .hiddenRow. Now follow the example, populate each <tr> with the unique_id
<tr uniqueId="<? echo $storageItem['unique_id']; ?>">
dedicate one column to activate the child row by adding a .details-control and instead of calling the function format() as in the example, do a
row.child(content[tr.attr('uniqueId')]).show();
Update. Jguy, what about
1) fist make your code to work only by inserting simple content. For example row.child('hello').show(); By that you will know that part is working.
2) Then, build up the content array separetely. You do not have to do it all in the same foreach(). This may improve the chance of success if you split the things up in "logical" operations.
3) remember to set an item_id on the <tr>'s
4) your dataTables version cannot be outdated in this context as long as you are using 1.10.x

Categories