Javascript dynmaic table from filter - javascript

I first create the table layout(headers like this):
//DB Connection already established
$sql = "SHOW COLUMNS FROM fairtrade;";
$result = $dbConnection->query($sql);
if($result->num_rows > 0){
echo "<th> </th>";
while($row = $result->tech_assoc()){
echo "<th>" . $row['Field'] . "</th>";
}
}
This works just fine. And then i fill the table with the data.(It's a huge table, thats why i will only give a short example):
//DB Connection already established
$sql = "SELECT * FROM fairtrade;";
$result = $dbConnection->query($sql);
if($result->num_rows > 0 ){
while($row = $result->fetch_assoc()){
//use div to be able to resize the cells
echo "<tr><td><div class="tablediv">" . $row['ID'] . "</div></td>
<td><div class=tablediv>" . $row['Gender'] . "</div></td></tr>";
}
}
So this works just fine aswell. I got a <select id=filter_for> and an <input type=text id=filter_value> and javascript is doing the filtering like this:
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i,countert,counterval;
input = document.getElementById("filter_value");
filter = input.value.toUpperCase();
table = document.getElementById("fairtrade_table");
tr = table.getElementsByTagName("tr");
countert = document.getElementById("filter_for");
counterval = countert.options[countert.selectedIndex].value;
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[counterval];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
This again, works fine. And depending on the selected value from the <select> it searches the column for that specific value.
So. How could I change this filter?
I want to be able to search for multiple things.
For example, you have a table with four Columns [ID][GENDER][LASTNAME][NAME]. If someone selected multiple values (for example 2) [GENDER] and [NAME]. The filter searches in both columns. Where the values are separated by ",". So my input would look like this: "Male, George". This should give me all the information about every Male who's name is George.
Second question.
Is it possible to change this filter or add a new one for the table head? Let's take the example from above, four columns. But now we only want the as the criteria (because the select has all values from the table head). So the select has the values ID, Gender, Lastname, Name. If I select ID then I only see the ID Column(BUT ALL ROWS), if I select ID and GENDER then both of these columns are shown with all rows. How is this possible?
Anything i found when googling "Javascript table filter" were one value filters.
Thanks for your time.

Related

how to obtain the drop down selected option from a dynamic table

I am trying to extract selected option from a dynamically created table column. The code below works to extract the input values but not for the drop down values.
Dynamically generate HTML
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='Letter"+i+"' type='text' placeholder='Letter' class='form-control input-md' /> </td><td><input name='Start"+i+"' type='text' placeholder='Start' class='form-control input-md'></td><td><input name='End"+i+"' type='text' placeholder='End' class='form-control input-md'></td> <td> <select name='cars' id='cars'><option value='All'>All</option><option value='Even'>Even</option><option value='Odd'>Odd</option></select></td>");
javascript code
// start from the second row as the first one only contains the table's headers
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// loop over the contents of each row
for (let j = 0; j < targetTableRows[i].cells.length; j++) {
// something we could use to identify a given item
let currColumn = tableHeaders.cells[j].innerHTML;
// the current <td> element
let currData = targetTableRows[i].cells[j];
// the input field in the row
let currDataInput = currData.querySelector('input');
// is the current <td> element containing an input field? print its value.
// Otherwise, print whatever is insside
currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`)
: console.log(`${currColumn}: ${currData.document.getElementById("addressType")}`);
if (currDataInput) {
Inventorydict[currColumn.replace(/\s/g, '')] = currDataInput.value;
} else {
Inventorydict[currColumn.replace(/\s/g, '')] = currData.innerHTML;
}
}
I use this to get the input values
let currDataInput = currData.querySelector('input');
I tried using this to get the selected option
let addresstype = currColumn.getElementById("addressType")
but it does not work. How can I obtain the drop down selected option ?
currColumn is being given a value in this point of your code:
let currColumn = tableHeaders.cells[j].innerHTML;
The innerHTML property returns a string, that's why you cannot use querySelector on it.
First of all, if you want to get the value of the select once every row, you should move that section outside of that inner cycle, that loops through each cell of that row.
Then, you will need to get a reference of the tr html element. This should be targetTableRows[i].
You can get your select element by using the querySelector on this element:
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// ...
let select = targetTableRows[i].querySelector("select");
let selectValue = select.value; // This will map to the "value" property of the selected option
}
However, please keep in mind that you should really select elements based on their class or input name, not by their type. Also, you should not assign the same id to multiple element of your page. This will help you avoid errors that will be hard to troubleshoot.

Looping through dynamically generated checkboxes to get values

I have a list of categories for products on my site and am trying to allow products to be listed under multiple categories.
When creating a product there is a list of categories with checkboxes generated from PHP like so:
$sql = "SELECT * FROM categories";
$stmt = DB::run($sql);
$categoryCount = $stmt->rowCount();
if ($categoryCount > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
$category_name = $row["category"];
$category_checkboxes .= "<input type='checkbox' value='$id' name='cat_$id' id='cat_$id'> $category_name<br />";
}
}
I created a hidden input to determine the amount of available categories
<input type="hidden" name="cat_count" id="cat_count" value="<?php echo $categoryCount; ?>">
I am then trying to loop through these in JS to get which ones were selected to send via AJAX to my parsing script to add to the DB.
var categories;
var cat_count = document.getElementById("cat_count").value;
var i;
for(i=1; i<=cat_count; i++){
var cat_id = 'cat_'+i;
var cat = document.getElementById(''+cat_id+'').value;
categories += cat+',';
}
I have two issues with this:
First a category can be deleted so although there might be 3 categories these could have ID's like '1,3,5'. So my checkboxes will have these ID's but the JS is looking for '1,2,3' and it obviously gets an error when it is trying to get the value of a NULL element.
Second, if it can get the values, it will get all of the values of all checkboxes not just the ones that are checked which is what I need. Although if I get a way to loop through the ID's correctly this shouldn't be too difficult to but in a if checked condition.
Any suggestions or assistance with this would be greatly appreciated.
Here is a cleaner way to do this. You don't need cat_count; Add a class to your checkboxes, select all of them, get their value and append it to the categories variable; Working fiddle
var categories = "";
var checkboxes = Array.from(document.getElementsByClassName("checkbox"));
checkboxes.forEach(function(element, index) {
categories += element.value;
});
Id need to be unique so this line var cat_count = document.getElementById("cat_count").value; will always return a single element.
Change it by adding index to it
Instead of Id you can use name with
document.getElementsByName("'cat_$id'")
Thanks to #CBroe for getting there first, that worked for me.
var categories = '';
var category = document.getElementsByClassName("product_category");
var i;
for(i=0; i<category.length; i++){
if(category[i].checked == true){
var category_value = category[i].value;
categories += category_value+',';
}
}

Filter out data from jquery datatables based on data attribute

I have jquery datatable which contains the data pulled from database. By default there's no filtering and it has all the data necessary for that user. There's custom search in input fields in addition to jquery datatables own search. Now i'd like to implement a checkbox action where if checkbox is checked, data is filtered out based on element data-attribute.
This is the checkbox:
<div class='checkbox' id='subplayers'>
<label><input type='checkbox' value=''>Show filtered content</label>
</div>"
The first column of the datatables is a <td> element with an attribute data-insub=x where x is 1 || x is 0 (<td data-insub='1'> or <td data-insub='0'>).
In script i detect the checkbox change:
$('#subplayers').change(function() {
if($(this).is(":checked")) {
//Checked
var playersInSub = document.querySelectorAll("[data-insub='1']");
}
else{
//Not checked
}
});
Now i'd like to filter out all the players who have data-attribute data-insubset as 0 (keep the ones which have it as 1). I think simple search is not sufficient here as this works on data written in table not on data attribute.
This is the PHP which is generating the table row data (more of an informative part of my code as i don't think it's relevant to the problem i'm having.).
$pid = $player['pid'];
$fname = $player['fname'];
$lname = $player['lname'];
$club = $player['club'];
$sameTourney = false;
if (in_array($pid, $playerIds)){
$sameTourney = true;
}
$sameSub = false;
if (in_array($pid,$subPlayers)){
$sameSub = true;
}
echo "<tr id='col+'".$playernumber."_filter'>";
if ($sameSub){
echo "<td class='playernumber' data-insub='1'>".$playernumber."</td>";
}
else{
echo "<td class='playernumber' data-insub='0'>".$playernumber."</td>";
}
echo "<td class='firstnames'>".$fname."</td>";
echo "<td class='lastnames'>".$lname."</td>";
echo "<td class='clubnames'>".$club."</td>";
if ($sameTourney){
echo "<td><a href='#' class='modifyplayer' id='removeModify".$pid."' data-actiontype='remove' data-playerid='".$pid."'>Remove</a></td>";
}
else {
echo "<td><a href='#' class='modifyplayer' id='addModify".$pid."' data-actiontype='add' data-playerid='".$pid."'>Add</a></td>";
}
echo "</tr>";
$playernumber += 1;
You can use jQuery hide() and show()
Hide all rows with attribute data-insub="1" use:
$("table").find("[data-insub='1']").hide();
Show all rows with attribute data-insub="1" use:
$("table").find("[data-insub='1']").show();
As i couldn't find a way to do it with data attributes, i made classes for my rows - if i wish to filter it out i added class allplayers and if i wished it to stay i added class insub.
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
var myRowClasses = oSettings.aoData[iDataIndex].nTr.className.split(" ");
if($("#subplayers").is(":checked")) {
return myRowClasses.indexOf('insub') > -1;
}
else{
return myRowClasses.indexOf('allplayers') > -1;
}
});
The trick is that elements who have class insub need to have class allplayersas well.

Auto increment text box value on dynamically generated table rows

I am populating max + 1 serial number from database to a text box in table row which can be dynamically generated into multiple rows. As a result I need the serial number to auto increase and decrease when adding and deleting rows.
Here are my codes:
PHP
<?php
include("connection.php");
$selectQuery = mysqli_query($connection,"SELECT MAX(SlNo) AS MaxSerial FROM cashsheet");
while($row = mysqli_fetch_assoc($selectQuery)){
$serialNumber = $row['MaxSerial'];
$maxSerial = $serialNumber + 1;
}
?>
<td><input type="text" class="form-control" name="serial[]" value="<?php echo $maxSerial; ?>"></td>
And this is my javascript to dynamically add rows into the table.
var $tr = $('table.dynamicTable tr.cloneme:first').clone();
addDP($('input.datepicker'));
$('#addMore').on('click',function(){
var clone = $tr.clone();
console.log(clone);
clone.append("<td><button class='deleteAdded btn btn-danger hvr-float-shadow'><span class='glyphicon glyphicon-remove-circle'></span>Remove</button></td>");
addDP(clone.find('input.datepicker'));
$('table.dynamicTable').append(clone);
});
$(document).on('click','.deleteAdded',function(){
$(this).closest('tr').remove();
});
Can somebody please tell me how to go about doing this. I Googled a lot but couldn't find anything. Thank you

How to get HTML table row data, based on checkbox selection in each row?

I have a table dynamically created with java script.It has one checkbox in each row as the first column.I want to fetch the row data based on the checkboxes selected of respective rows.
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = 'Select';
cell1.innerHTML = 'Epic';
cell0.innerHTML = " checkbox html code ";
cell1.innerHTML = epicSeries[j];
Actually too many columns are there I am putting just two of them. I have lot of epics down the column header 'epic' and one checkbox as the first column in each row.I want row data based on checkbox selcted.
Sorry code was too long so I cant paste all of them.
Having now an example of your code and bit more clear requirement, i think you should do the folowing:
$('#myTable input[type=checkbox]:checked').each(function() {
var row = $(this).parent().parent();
var rowcells = row.find('td');
// rowcells contains all td's in the row
// you can do
// rowcells.each(function() {var tdhtml = $(this).html(); });
// to cycle all of them
});
If you have table like that:
<table>
<tr>
....
<td><input type="checkbox" name="cb1" checked></td>
...
</tr>
</table>
This code will return all <tr>'s with checked checkboxes
If row selecting check box is in a deeper level you should as more .parent()'s as needed
This exemple uses jQuery of course.
$('table#tableid input[type=checkbox]').each(function() {
if ($(this).is(':checked')) {
....
}
});
something like that i supose
This is what I used in my case using jquery:
$('.chkbox').click(function(){
var row = jQuery(this).closest('tr');//your nearest row for the check box
$(row).each(function(){
//get all data using the id and use/store it
$(this).find(".item").html();
});
});
For each checkbox and for each item in a row give a class(I used chkbox for all checkboxes and item, price etc. for all items of a single row)

Categories

Resources