Bootstrap 4 - DataTable search not working on rows added by jQuery - javascript

I have a problem with the Bootstrap 4 search tool. If the rows are added manually in tbody the search works, but if I add a new row from jQuery then search doesn't see those rows.
This is the body of the table.
Below is the function that adds a new row to the table:
function addProduct(name, id, price, quantity = 1)
{
var template = $("#product-template").clone(true, true);
var existingRow = $("#product-table").find('#product' + id);
template.removeClass("disabled");
if (existingRow.length > 0)
{
var quantity = parseInt(existingRow.find('.prod-quantity').text()) + 1;
existingRow.find('.prod-quantity').text(quantity);
calculateTotalPrice(id);
return;
}
template.attr("unit-price", price);
template.attr("id", "product" + id);
template.find('.prod-name').attr("title", name);
template.attr("productID", id);
template.find('.prod-name').text(name);
template.find('.prod-quantity').text(quantity);
template.find('.total-price').text(price);
$(template).css("display", "table-row");
$("#product-table").append(template);
calculateTotalPrice(id);
orderTableData();
calculateTotalPayment();
}
<tbody id="product-table" class="prd">
<tr id="product-template" class="tr-prod disabled">
<td class="text-center nr-order" id=""></td>
<td class="prod-name" contenteditable="true" title="" style="background-color: white; color:black;">a</td>
<td class="prod-quantity text-center" contenteditable="true" style="background-color: white; color:black">1</td>
<td class="total-price text-center"></td>
<td class="col-sm-3 text-center " style="width: 25px!important;">
<i class="fas fa-minus-circle remove" title="Elimină" style="font-size:20px;color:#F08080;width:20px">
</i>
</td>
</tr>
<tr id="product-template-1" class="tr-prod disabled">
<td class="text-center nr-order" id=""></td>
<td class="prod-name" contenteditable="true" title="" style="background-color: white; color:black;">b</td>
<td class="prod-quantity text-center" contenteditable="true" style="background-color: white; color:black">1</td>
<td class="total-price text-center"></td>
<td class="col-sm-3 text-center " style="width: 25px!important;">
<i class="fas fa-minus-circle remove" title="Elimină" style="font-size:20px;color:#F08080;width:20px">
</i>
</td>
</tr>
</tbody>
I don't know why, but the rows added with the addProduct() function don't appear in the search, and not only that, but they disappear completely when I'm searching for something.
What am I missing, maybe I should update the table after I add a new row?

<script>
$(document).ready(function () {
var table = $('#product-table').DataTable();
$('.dataTables_length').addClass('bs-select');
function addProduct(name, id, price, quantity = 1)
//instead $("#product-table").append(template)
table.row.add([
'td 1',
'td 2',
'td 3',
...
'td n',
])
table.draw();
}
});
</script>

Related

table javascript pagination and sorting

How Can I search and paginate Table? Also, how to sort all cols ascending and descending? Now I can do it only in one way.
Table loads data from javascript.
const users = [
{
obec: 'Bratislava',
okres: 'Bratislava',
kraj: 'Bratislavský',
obyvatelov: 411228,
celkovo: 1,
eco: 1,
peo: 1,
gov: 131,
mob: 203,
env: 81,
liv: 3 }];
//LOAD DATA
let data = users.map(createRow);
$('tbody').html(data);
// SORT TABLE
$('table thead td').on('click', e => {
let $this = $(e.currentTarget);
// Hide / show caret
$('.fa-caret-down').hide();
$this.find('.fa-caret-down').show();
// Get type and sort data
let type = e.target.id;
let sorted = sort(users, type);
// Create rows and set table HTML
let data = sorted.map(createRow);
$('tbody').html(data);
});
function createRow(user) {
let row = `<tr>
<td>${user.obec}</td>
<td>${user.okres}</td>
<td>${user.kraj}</td>
<td>${user.obyvatelov}</td>
<td>${user.celkovo}</td>
<td>${user.eco}</td>
<td>${user.peo}</td>
<td>${user.gov}</td>
<td>${user.mob}</td>
<td>${user.env}</td>
<td>${user.liv}</td>
</tr>`;
return row;
}
function sort(obj, type) {
let sorted = obj.sort((b, a) =>
type === 'obyvatelov' ? b.obyvatelov - a.obyvatelov :
type === 'celkovo' ? b.celkovo - a.celkovo :
type === 'eco' ? b.eco - a.eco :
type === 'peo' ? b.peo - a.peo :
type === 'gov' ? b.gov - a.gov :
type === 'mob' ? b.mob - a.mob :
type === 'env' ? b.env - a.env :
type === 'liv' ? b.liv - a.liv :
a.obec.localeCompare(b.obec));
return sorted;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- partial:index.partial.html -->
<table class="table table-striped table-bordered" cellspacing="0" style="width:100%;">
<thead>
<tr>
<td id="obec">Obec <i class="fa fa-caret-down"></i></td>
<td id="okres">Okres</td>
<td id="kraj">Kraj</td>
<td id="obyvatelov">Počet obyvateľov <i class="fa fa-caret-down"></i></td>
<td id="celkovo">Celkové poradie<i class="fa fa-caret-down"></i></td>
<td id="eco">Economy <i class="fa fa-caret-down"></i></td>
<td id="peo">People <i class="fa fa-caret-down"></i></td>
<td id="gov">Governance <i class="fa fa-caret-down"></i></td>
<td id="mob">Mobility <i class="fa fa-caret-down"></i></td>
<td id="env">Environment <i class="fa fa-caret-down"></i></td>
<td id="liv">Living <i class="fa fa-caret-down"></i></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script><script src="new.js"></script>
I am new in javascript and can not solve this. I red whole internet but no luck.
This is how I want to look it like.

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

Display attribute from a JSON in title (angularjs)

Im having problems displaying the Title of a table.
This is where i click to open a "modal" with the details:
<td>{{z.proyecto}}</td>
Here is the modal that opens up with details of said project:
<div id="proyecto_detalle" class="modal" style="display: {{estiloProyecto_detalle}};">
<div class="modal-content">
<span class="close" ng-click="close_proyecto_detalle()">×</span>
<h4 align="center">Detalle Tareas</h4>
<table id="detalleTareas" class="table table-striped table-bordered">
<thead>
<tr>
<td><b>Tarea</b></td>
<td><b>Inicio</b></td>
<td><b>Termino</b></td>
<td><b>Completado</b></td>
<td><b>Esperado</b> </td>
<td><b>Responsable</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="y in datos10">
<td style="vertical-align: top;">{{y.tarea}}</td>
<td style="vertical-align: top;">{{y.inicio}}</td>
<td style="vertical-align: top;">{{y.termino}}</td>
<td style="vertical-align: top;">{{y.completado}}%</td>
<td style="vertical-align: top;">{{y.esperado}}%</td>
<td style="vertical-align: top;">{{y.nombre}}</td>
</tr>
</tbody>
</table>
</div>
</div>
I need to show the name of "z.proyecto" inside the modal in the "h4" where it says "Detalle Tareas".
Any tips about how can i do it?
This is my angularjs, where i display the modal, updated with the current changes.
$scope.mostrar_proyecto = function(project_id, proyecto) {
$http.get("conector.php?tipoDato=query10&project_id="+project_id)
.then(function(response) {
$scope.mensajeEspera = "";
$scope.datos10 = response.data;
for(var i = 0; i < $scope.datos10.length; i++){
var currentObj = $scope.datos10[i];
console.log(currentObj);
currentObj.tituloObj = currentObj.proyecto;
$scope.titulo = currentObj.tituloObj;
currentObj.titulo = currentObj.tituloObj;
}
$scope.titulo = currentObj.tituloObj;
});
$scope.estiloProyecto_detalle = "block";
}
I think you could update your function mostrar_proyecto like this:
function mostrar_proyecto(id){
//...your previous code
//update
//...retrieve project data: z.proyecto and bind it
$scope.title = z.proyecto; //or your specific data (titulo de la tarea, detalles, or any other)
}
and now in your modal just bind the h4 to that var like this:
<h4 align="center" data-ng-bind="title"></h4>

Jquery datatable fnFilter is not work in some conditions

In my code i use fnFilter function of Jquery datatable to search the data.
In some cases it search perfectly but in some cases it not.
if i try to search code = "BS" it will search perfectly.
But when i try to search using code = "AL" it will display all records. which is not correct.
This is my code for datatable search option.
$("div.dataTables_filter input").bind('keypress', function (e) {
var searchText = $(this).val().trim();
if (e.which == 13) {
$("#search-error-text").remove();
if (searchText.length > 0) {
var value = searchText;
oTable.fnFilter(value);
$("div.dataTables_filter input").val(searchText);
}
else {
var errorMessage = "Please Enter Data!";
$("div.dataTables_filter input").before("<span id='search-error-text' class='error-text'>" + errorMessage + "</span>");
return;
}
}
else {
return;
}
});
$("div.dataTables_filter #grid-search-button").click(function () {
$("#search-error-text").remove();
var searchText = $("div.dataTables_filter input").val().trim();
if (searchText.length > 0) {
var value = searchText;
oTable.fnFilter(value);
$("div.dataTables_filter input").val(searchText);
}
else {
var errorMessage = "Please Enter Data!";
$("div.dataTables_filter input").before("<span id='search-error-text' class='error-text'>" + errorMessage + "</span>");
return false;
}
});
Html code below table.
<div class="table-responsive">
<table id="datatable-sale" class="datatable">
<thead>
<tr>
<th class="table_heading table-head ">
Code
</th>
<th class="table_heading table-head">
Description
</th>
<th class="table_heading table-head">
Type
</th>
<th class="table_heading table-head cursorDefault">
Edit
</th>
<th class="table_heading table-head cursorDefault">
Status
</th>
<th class="table_heading table-head cursorDefault">
Delete
</th>
</tr>
</thead>
<tbody class="table-head">
#foreach (var item in ViewData["sale"] as IEnumerable<Sales_lut>)
{
<tr>
<td class="table_heading text-left table-head-maintenance Width-10">
#item.code
</td>
<td class="table_heading text-left">
#item.descrip
</td>
<td class="table_heading text-left table-head-maintenance Width-10">
#item.type1
</td>
<td class="table_heading">
<a id="edit_sale" href="#" class=" edit action-button permission-based-access" saleidval="#item.saleid" permission-key="#Permissions.Sale.GetText()" sale-code="#item.code">
<i class="icon-pencil input-icon success" title="Edit">
</i>
</a>
</td>
<td class="table_heading permission-based-access" permission-key="#Permissions.Sale.GetText()">
#if (item.status == 0)
{
<a class="active" href="" title="Change Status" active-id="#item.saleid" sale-code="#item.code" active-code="#item.code">
<img id="active" src="#Url.Content("~/Content/Images/tick.png")" />
</a>
}
else
{
<a class="in-active" href="" title="Change Status" in-active-id="#item.saleid" sale-code="#item.code" in-active-code="#item.code">
<img id="in-active" src="#Url.Content("~/Content/Images/bullet_cross.png")" />
</a>
}
</td>
<td class="table_heading">
<a id="delete_sale" class=" deletesale delete permission-based-access" permission-key="#Permissions.Sale.GetText()" href="#" sale-code="#item.code">
<i class="icon-trash" title="delete">
</i>
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
Attach screenshot display an actual issue.Code "FZ" and "AM" does not contain any word as "AL" then also it display this records. and this happen for multiple search options. I need to apply search for whole data so i can't use single column search option.I just find out one issue that it search alternate rows means it search only odd rows in the grid. Any solution for it ???

AngularJS Displaying Table Row on expansion

I am trying to show a more detailed summary of a row when a user clicks on the "+" icon on the row. I got it to work when I used an tag but when I modified it to an tag, the javascript would not kick in.
Here's what I have:
<table class="table" ng-repeat="lineItem in order.OrderLineItems">
<tbody >
<tr >
<td class="col-md-3"><a ng-hide="!lineItem.OrderLineItemModifiers.length " class="glyphicon glyphicon-plus" ng-model=show></a> <b>Item</b></td>
<td class="col-md-3">{{lineItem.Name}}</td>
<td class="col-md-3">{{lineItem.Quantity}}</td>
<td class="col-md-3">{{lineItem.TotalPrice}}</td>
</tr>
<tr ng-repeat="modifiers in lineItem.OrderLineItemModifiers" ng-show="show">
<td class="col-md-3"></td>
<td class="col-md-3 ordermodifier">{{modifiers.Name}}</td>
<td class="col-md-3"></td>
<td class="col-md-3 ">{{modifiers.TotalPrice}}</td>
</tr>
</tbody>
</table>
<div><b>Total Amount: {{order.TotalAmount}}</b></div>
And in the Javascript file:
app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, order) {
$scope.toggleDetail = function ($index) {
$scope.activePosition = $scope.activePosition == $index ? -1 : $index;
};
});
What I am confused about is why would this work if I used an tag instead of an ? With the current code above, I would click on the "+" and it would not expand the row to show the modifier rows
Thank you!
<td class="col-md-3"><a ng-hide="lineItem.OrderLineItemModifiers.length !== 0 " class="glyphicon glyphicon-plus" ng-model=show></a> <b>Item</b></td>
try this. not sure what problem you had.

Categories

Resources