My addrow button in DataTables is not working - javascript

I am trying to create a button that can help me to add a row into a DataTables table and still remain every element in each column.
I don't know why my code didn't work.
var table = null;
var arrData = [];
var arrDataPG = [];
arrData.push({
STT: 1,
id: 1,
product_type: "",
condition: "",
cashback: 0.0,
note: ""
});
$('#addRow').on('click', function () {
console.log(arrData.length);
if (arrData != '') {
var ida = arrData[0].id;
} else {
var ida = 1;
}
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].id > ida) {
ida = arrData[i].id;
}
};
arrData.push({
STT: ida + 1,
id: ida + 1,
product_type: "",
condition: "",
cashback: 0.0,
note: ""
});
if (table != null) {
table.clear();
table.rows.add(arrData).draw();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="example" class="cell-border hover" style="width:100%">
<thead>
<tr>
<th>STT</th>
<th>Loại sản phẩm*</th>
<th>Điều kiện áp dụng</th>
<th>Rebate(%)*</th>
<th>Ghi chú</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="sorting_1" style="width:50px">
1
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="product_type"></textarea>
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="condition"></textarea>
</td>
<td>
<input type="number" id="cashback">
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="note"></textarea>
</td>
<td>
<div class="btn btn-danger remove" id=""><i class="fa-solid fa-ban"></i></div>
</td>
</tr>
</tbody>
</table>
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>

you need to initialise the DataTable before you can add the data to it - once that's done, you need to tell it about the shape of your data. You're also running into an issue that the data you've got in arrData is overwriting your input fields - so I moved the inputs into the table footer; that seems to make the most sense, TBH.
const arrData = [{
STT: 1,
id: 1,
product_type: "Car",
condition: "Poor",
cashback: 20,
note: "Well knackered"
}]
const table = $('#example').DataTable({
data: arrData,
columns: [{
data: 'STT'
},
{
data: 'product_type'
},
{
data: 'condition'
},
{
data: 'cashback'
},
{
data: 'note'
},
{
data: 'id',
visible: false
}
]
})
$('#addRow').on('click', function() {
let ida = null
if (arrData != '') {
ida = arrData[0].id
} else {
ida = 1
}
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].id > ida) {
ida = arrData[i].id
}
}
arrData.push({
STT: ida + 1,
id: ida + 1,
product_type: $('#product_type').val(),
condition: $('#condition').val(),
cashback: $('#cashback').val(),
note: $('#note').val(),
})
table.clear()
table.rows.add(arrData).draw()
$('#product_type').val('')
$('#condition').val('')
$('#cashback').val('')
$('#note').val('')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js
<table id="example" class="cell-border hover" style="width:100%">
<thead>
<tr>
<th>STT</th>
<th>Loại sản phẩm*</th>
<th>Điều kiện áp dụng</th>
<th>Rebate(%)*</th>
<th>Ghi chú</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td class="sorting_1" style="width:50px">
1
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="product_type"></textarea>
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="condition"></textarea>
</td>
<td>
<input type="number" id="cashback">
</td>
<td>
<textarea class="form-control text-primary" style="width:300px;" id="note"></textarea>
</td>
<td>
<div class="btn btn-danger remove" id=""><i class="fa-solid fa-ban"></i></div>
</td>
</tr>
</tfoot>
</table>
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>
Hopefully, that will get you on the right track. The thing to take the most notice of is your initialisation of the DataTable; once that's there, you should be fine.

Related

Reset calculation after adding row to table

I'm trying to add row to table dynamically and calculates the age from ID card number.
ID card number for example: 88xxxxxxxxxx (age 33) // 00xxxxxxxxxx (age 21) // 01xxxxxxxxxx (age 20) and so on.
Problem here, as I'm adding row to the table. First row works fine but for the following rows, the results of age selector is applied to all rows in the table.
I've tried to clear the input of age class as new rows are added but seems like it removes all the input of the age selector as well.
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(".noic").val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
You need to use $(this) to get a reference to the currently blurred .noic, and use it as a reference to access itself and it's sibling elements:
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(this).val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(this).closest("tr").find(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>

How to get total of cart items price and multiply with quantity in Vue.js

I am working on the cart system in Vue.js and want to display the sum of product price by multiplication with product quantity. recently I am working in PHP and get this done by array_sum()....
I have a cartData[] in which I am getting the values from the backend using Axios and in an array, there is a value called product_price. i was trying to achieve this with reduce method but it return NaN Thanks in advance
<table id="cart" class="table table-hover table-condensed cart_table">
<!-- <span class="d-none">{{ index }}</span> -->
<thead>
<tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:8%">Color-Size</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody v-for="(cart, index) in cartData" :key="cart.id">
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-2 hidden-xs">
<img
:src="
require(`../assets/product_images/${cart.product_image}`)
"
class="img-responsive"
/>
</div>
<div class="col-lg-10">
<span class="d-none">{{ index }}</span>
<h4 class="nomargin">{{ cart.product_title }}</h4>
</div>
</div>
</td>
<td data-th="Price">${{ cart.cart_price }}</td>
<td data-th="Quantity">
<input
type="number"
class="form-control text-center"
v-bind:value="cart.qty"
/>
</td>
<td data-th="Color-size">
<span> {{ cart.product_color }} - {{ cart.product_size }} </span>
</td>
<td data-th="Subtotal" class="text-center">
{{ cart.cart_price * cart.qty }}
</td>
<td class="actions" data-th="">
<button class="btn btn-info btn-sm">
<i class="fas fa-sync"></i>
</button>
<button class="btn btn-danger btn-sm">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<a href="#" class="btn btn-warning"
><i class="fa fa-angle-left"></i> Continue Shopping</a
>
</td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center">
//here i want to get the sum
<strong>Total {{ total }}</strong>
</td>
<td>
<a href="#" class="btn btn-success btn-block"
>Checkout <i class="fa fa-angle-right"></i
></a>
</td>
</tr>
</tfoot>
</table>
Vue.js script
import axios from "axios";
export default {
name: "Cart",
data() {
return {
cartData: [],
};
},
created() {
this.getCartItems();
},
computed: {
total() {
return this.cartData.reduce((acc, item) => acc + item.product_price, 0);
}
},
methods: {
getCartItems() {
axios
.get("http://localhost/shopping_store/src/Api/api?action=getcartitems")
.then((res) => {
this.cartData = res.data.cart_Data;
})
.catch((err) => {
console.log(err);
});
},
},
};
data(){
return{
total: 0,
cartData: [{
price: 5,
qty: 5},
{price: 5,
qty: 5
}],
}
},
computed: {
calcSum(){
let total = 0;
this.cartData.forEach((item, i) => {
total += item.price * item.qty;
});
return total;
}
}
Based on your object example here is a simple code to get the sum of product price multiplied by product quantity
var cart_Data =[{"p_id":"44","cart_id":"10","cart_price":"100","product_title":"Slim striped pocket shirt","product_image":"product-4.jpg","product_color":"Blue","product_size":"L","qty":"3"},{"p_id":"45","cart_id":"11","cart_price":"42","product_title":"Contrasting Shrit","product_image":"product-7.jpg","product_color":"White","product_size":"M","qty":"1"}]
function total(cart_Data){
let sum=0
cart_Data.map(x=>{
sum = sum + (x.cart_price * x.qty)
})
return sum
}
console.log(total(cart_Data))

How to get data in an Editable Table to send via AJAX?

I have a modal and there is an Dynamic Editable table. I am seeking a way of getting the data of the editable table to the JS variables. Then I can pass these data to the controller via AJAX. I tried so many codes. but I couldn't find the suitable way. How should I get values to variables ?
Form blade
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="opening_invoice_table_body">
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[1][date]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[1][detail]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[1][invoice_no]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[1][amount]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>
Script
<script>
$(document).ready(function(){
var counter = 2;
//add rows
$("#add_row").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[' + counter + '][date]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[' + counter + '][detail]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[' + counter + '][invoice_no]"></td>';
cols += '<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[' + counter + '][amount]" min="0" step="any" placeholder="0.00"></td>';
cols += '<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>';
newRow.append(cols);
$("#opening_invoice_table").append(newRow);
counter++;
});
//delete rows
$("#opening_invoice_table").on("click", "#delete_row", function (event) {
$(this).closest("tr").remove();
counter -= 1
counter++
});
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
function newOpeningInvoice() {
var e = window.event || arguments.callee.caller.arguments[0];
e.preventDefault();
//Here I want to get table data. Below variables used for just testing purpose.
//var date = +$('.amount').val();
// var detail = $("input[class='detail']").val();
// var invoice_no = +$('.detail-no').val();
// var amount = +$('.amount').val();
// var date = "2020-03-27";
// var detail ="value";
//alert(amount);
$.ajax({
url: "opening_invoice/create",
type: "POST",
data: {'date': date, 'detail': detail, 'invoice_no': invoice_no, 'amount': amount, '_token':'{{csrf_token()}}' },
success: function (data) {
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
});
return false;
}
</script>
Okey well I think this code might help you a lot.
I recommend you to create the "dynamic" parts in the javascript itself. This way you can use the data easier in my opinion. Here is how:
Javascript:
//To use them globally in the script. NOTE: Needs to be above the onload, otherwise javascript does not know the elements yet.
let trElement;
let tdElement;
let inputElement;
window.onload = onload();
function onload() {
//Create elements
trElement = document.createElement("tr");
tdElement = document.createElement("td");
inputElement = document.createElement("input");
//Set elements parameters
inputElement.type = "date";
inputElement.classList.add("form-control", "form-control-alternative", "date");
inputElement.name = "opening_invoice[1][date]";
//Appends
tdElement.append(inputElement);
trElement.append(tdElement);
document.getElementById("opening_invoice_table_body").appendChild(trElement);
//I do not have jQuery installed but you should create them like this:
// let inputElement = $('<input/>', {
// 'class': 'form-control form-control-alternative date'
// 'name': ...
// });
}
function createPartOfATable() {
console.log(inputElement.value);
}
HTML:
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
//This part has changed. Removed the HTML inside this tbody since I create it in javascript.
<tbody id="opening_invoice_table_body"></tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row" onclick="createPartOfATable();"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
Keep in mind that I created it in pure Javascript since I did not have jQuery installed at the moment. But I wrote some examples on how you should do it. Also jQuery documentation gives you a lot of info to do it with jQuery.
I could find the answer and it is working fine. serialize() is used to send the array of dynamic table data via AJAX to the controller.
//add rows
$('#add_row').on('click', function () {
var tr = '<tr>'+
'<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>'+
'<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>'+
'<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>'+
'<tr>';
$('tbody').append(tr);
});
//delete rows
$('#opening_invoice_table').on('click', '#delete_row', function (event) {
var last=$('tbody tr').length;
if(last==1){
//do nothing
} else {
$(this).parent().parent().remove();
}
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
});
//submit opening invoice data
$('#opening_invoice_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"opening_invoice/create",
method:'post',
data:$(this).serialize(),
dataType:'json',
success:function(data)
{
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
})
});
<form id="opening_invoice_form">
#csrf
<div class="modal-body">
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success" id="sad"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>

Dynamically show and hide certain raw detail data on click?

I want to dynamically show and hide table row details on every button click, but every time I click on span glyphonic icon all tr's details data are open by default .what should i change to make visible this data only for those elements on which i have clicked? ( in my case i need to make visible only certain data on which user has clicked):
<form role="form">
<script cam-script type="text/form-script">
$scope.selectedRow = null;
var persons = $scope.persons = [
{
"id": 1,
"name": "name1",
"age":"454",
"description":"this is simple name"
} ,
{
"id": 2,
"name": "name2",
"age":"4543",
"description":"this is simple name"
},
{
"id": 3,
"name": "name2",
"age":"4543",
"description":"this is simple name"
}
];
camForm.on('form-loaded', function() {
camForm.variableManager.createVariable({
name: 'persons',
type: 'Array',
value: persons
});
});
$scope.pageNumber = 0;
$scope.IsHidden=true;;
$scope.setPageNumber = function(index) {
$scope.pageNumber = index;
$scope.IsHidden = $scope.IsHidden ? false : true;
}
</script>
<div class="container">
<table class="table table-condensed" style="border-collapse:collapse;">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th> </th>
</tr>
</thead>
<tbody ng-repeat="item in persons " >
<tr >
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td><button class="btn btn-default btn-xs" ><span class="glyphicon glyphicon-eye-open" ng-class="{$index == pageNumber }" ng-click="setPageNumber($index)($index)"></span></button></td>
</tr>
<tr ng-hide="IsHidden">
<td>
<label for="id" class="control-label">details</label>
<div class="controls">
<input id="description" class="form-control" type="text" ng-model="item.description" required readonly/>
</td>
</tr>
</tbody>
</table>
</div>
</form>
Here' the code you are looking for
var myApp = angular.module('myApp',[]);
myApp.controller('myController', ['$scope', function($scope) {
$scope.persons = [
{
"id": 1,
"name": "name1",
"age":"454",
"description":"this is simple name1"
} ,
{
"id": 2,
"name": "name2",
"age":"4543",
"description":"this is simple name2"
},
{
"id": 3,
"name": "name2",
"age":"4543",
"description":"this is simple name3"
}
];
$scope.toggle = function (index){
if($scope.persons[index].hidethis == undefined){
$scope.persons[index].hidethis = true;
}else{
$scope.persons[index].hidethis = !$scope.persons[index].hidethis;
}
}
}]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<table class="table table-condensed" style="border-collapse:collapse;">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th> </th>
</tr>
</thead>
<tbody ng-repeat="item in persons">
<tr>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td><button class="btn btn-default btn-xs" ng-click="toggle($index)"></button></td>
</tr>
<tr id="{{hideid + $index}}" ng-show="item.hidethis">
<td>
<label for="id" class="control-label">details</label>
<div class="controls">
<input id="description" class="form-control" type="text" ng-model="item.description" required readonly/>
</div>
</td>
</tr>
</tbody>
</table>
</form>

I need to filter bootstrap jQuery datatable

I need to filter datatable. I have already write code and its working but when i change the status by click on button then it is not working.
i.e: if there is enabled button i click on it then it will be changed to disabled button. Then if i filter table it is not working.
Same way if there is disable button and i click on it then it will change to enabled button but there is no effects on filtering datatable.
Filtering remains same although i am changing filter value.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<!-- HTML -->
<table id="data-table" class="table table-hover table-bordered table-stripped">
<thead>
<tr>
<th class="text-center">#</th>
<th>Category Name</th>
<th class="text-center filterable customFilterColumn">Status</th>
</tr>
<thead>
<tbody>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Enabled"><button class="btn btn-default btn-xs btn-status status-enabled">Enabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Enabled"><button class="btn btn-default btn-xs btn-status status-enabled">Enabled</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var table = $('#data-table').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"aaSorting": [
['1', 'asc']
],
/* "order": [], */
"columnDefs": [{
/* "targets": [0,-1], */
"targets": [0,-1],
"orderable": false
}]
});
function filter(source,customFilterColumn){
var count = 0;
var tableid = source.split(' ')[0];
$(source).each( function ( k ) {
if ($(this).text() !== '') {
if(++count==1){
$(tableid).parents("div.row:first").before('<div class="row"><div id="filtercontent"></div></div>');
}
var i = $(this).index();
var select = $('<select id="filer_'+i+'" class="form-control"><option value="">All</option></select>')
.insertBefore('#filtercontent')
.on( 'change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );
// Get the Status values a specific way since the status is a anchor/image
if ($(this).hasClass(customFilterColumn)) {
var dataFilterColumn = [];
/* ### IS THERE A BETTER/SIMPLER WAY TO GET A UNIQUE ARRAY OF <TD> data-filter ATTRIBUTES? ### */
table.column( i ).nodes().to$().each( function(d, j){
var thisStatus = $(j).attr("data-filter");
if($.inArray(thisStatus, dataFilterColumn) === -1) dataFilterColumn.push(thisStatus);
} );
dataFilterColumn.sort();
$.each( dataFilterColumn, function(i, item){
select.append( '<option value="'+item+'">'+item+'</option>' );
});
}
// All other non-Status columns (like the example)
else {
table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
});
}
$('#filer_'+i).wrapAll('<div class="col-sm-2 form-group"></div>');
$('<label>'+$(this).text()+'</label>').insertBefore('#filer_'+i);
}
});
$(tableid+'_wrapper').removeClass('form-inline');
}
filter('#data-table thead th.filterable','customFilterColumn');
$('.btn-status').click(function(){
var id = $(this).val();
var status = parseInt($(this).attr('status'));
$(this).toggleClass('status-enabled');
$(this).toggleClass('status-disabled');
if(status==0){
$(this).html('Enabled');
$(this).attr('status','1');
$(this).parent().attr('data-filter','Enabled');
}
else{
$(this).html('Disabled');
$(this).attr('status','0');
$(this).parent().attr('data-filter','Disabled');
}
});
});
</script>
Just use table.rows().invalidate().draw(); in your .btn-status click event. Issue is you are updating just html but not the datatable data. For more detail refer this link Datatable row invalidate
$(document).ready(function() {
var table = $('#data-table').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"aaSorting": [
['1', 'asc']
],
/* "order": [], */
"columnDefs": [{
/* "targets": [0,-1], */
"targets": [0, -1],
"orderable": false
}]
});
function filter(source, customFilterColumn) {
var count = 0;
var tableid = source.split(' ')[0];
$(source).each(function(k) {
if ($(this).text() !== '') {
if (++count == 1) {
$(tableid).parents("div.row:first").before('<div class="row"><div id="filtercontent"></div></div>');
}
var i = $(this).index();
var select = $('<select id="filer_' + i + '" class="form-control"><option value="">All</option></select>')
.insertBefore('#filtercontent')
.on('change', function() {
var val = $(this).val();
table.column(i)
.search(val ? '^' + $(this).val() + '$' : val, true, false)
.draw();
});
// Get the Status values a specific way since the status is a anchor/image
if ($(this).hasClass(customFilterColumn)) {
var dataFilterColumn = [];
/* ### IS THERE A BETTER/SIMPLER WAY TO GET A UNIQUE ARRAY OF <TD> data-filter ATTRIBUTES? ### */
table.column(i).nodes().to$().each(function(d, j) {
var thisStatus = $(j).attr("data-filter");
if ($.inArray(thisStatus, dataFilterColumn) === -1) dataFilterColumn.push(thisStatus);
});
dataFilterColumn.sort();
$.each(dataFilterColumn, function(i, item) {
select.append('<option value="' + item + '">' + item + '</option>');
});
}
// All other non-Status columns (like the example)
else {
table.column(i).data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>');
});
}
$('#filer_' + i).wrapAll('<div class="col-sm-2 form-group"></div>');
$('<label>' + $(this).text() + '</label>').insertBefore('#filer_' + i);
}
});
$(tableid + '_wrapper').removeClass('form-inline');
}
filter('#data-table thead th.filterable', 'customFilterColumn');
$('.btn-status').click(function() {
var id = $(this).val();
var status = parseInt($(this).attr('status'));
$(this).toggleClass('status-enabled');
$(this).toggleClass('status-disabled');
if (status == 0) {
$(this).html('Enabled');
$(this).attr('status', '1');
$(this).parent().attr('data-filter', 'Enabled');
} else {
$(this).html('Disabled');
$(this).attr('status', '0');
$(this).parent().attr('data-filter', 'Disabled');
}
table.rows().invalidate().draw();
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<!-- HTML -->
<table id="data-table" class="table table-hover table-bordered table-stripped">
<thead>
<tr>
<th class="text-center">#</th>
<th>Category Name</th>
<th class="text-center filterable customFilterColumn">Status</th>
</tr>
<thead>
<tbody>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled" status="0">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled" status="0">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Enabled"><button class="btn btn-default btn-xs btn-status status-enabled" status="1">Enabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Disabled"><button class="btn btn-default btn-xs btn-status status-disabled" status="0">Disabled</button></td>
</tr>
<tr>
<td class="text-center"><input type="checkbox" class="minimal" /></td>
<td>Shoes</td>
<td class="text-center" data-filter="Enabled"><button class="btn btn-default btn-xs btn-status status-enabled" status="1">Enabled</button></td>
</tr>
</tbody>
</table>
</div>
</div>

Categories