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
Related
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.
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+',';
}
}
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.
A Product List is created using the PHP code each product having its own checkbox, I have used the Java Script code to get values of all the selected checkboxes now i need to call an other PHP page which will receive this string data and populate all the selected products list. Can you please tell me the way i can use to send data to another php page using javascript POST method.
Code used to create the product list and get value of selected checkboxes is as follows :
<?php
$cnt=0;
$rslt = mysqli_query($conn,"SELECT Icode,Name,Size,Style FROM productinfo");
if(!$rslt)
{
die(mysqli_error($conn));
}
else
{
echo " <table width='100%'>";
while($row = mysqli_fetch_assoc($rslt))
{
if($cnt==0)
{
echo "<tr>";
}
echo "<td width='30%'>
<div class='card'>
<img src='upload/"."download.jpg"."' alt='Avatar' style='width:100px' >
<div class='container'>
<h4><b>".$row['Name']." <input type='checkbox' name='prodchklist' value=".$row['Icode']." '/> </b></h4>
<p>".$row['Size']."</p>
<p>".$row['Icode']."</p>
</div>
";
?>
</div>
<?php
echo "</td>";
if($cnt==2)
{
$cnt=0;
echo "</tr>";
}
else
$cnt = $cnt + 1;
}
}
echo "</table>";
?>
</div>
<button id="SendInquiry" style="display: block;">Send Inquiry</button>
<script type='text/javascript'>
$(document).ready(function(){
$('#SendInquiry').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length +"checkboxes are checked";
result.each(function(){
resultstring+=$(this).val();
}
);
$('#divrslt').html(resultstring);
}
else
{
$('#divrslt').html("nothing checked");
}
});
});
</script>
I don't know your reason to use javascript for collecting checkbox values and post it to another PHP page. You can achive what you want without javascript:
Wrap you checkboxes inside a form, set its action to second page, and don't forget to set its method to POST, eg:
<form action="second.php" method="post">
</form>
Put [] at the end of checkbox name to make it array that can send multiple values with one name, eg:
<input type="checkbox" name="prodchklist[]" value="item1">
<input type="checkbox" name="prodchklist[]" value="item2">
<input type="checkbox" name="prodchklist[]" value="item3">
But, if you really want to use javascript to call the second page, for example by using ajax, do this:
Store the selected values in an array, instead of appending each values in one variable.
// add this, to store the data you want to post
var data = {
prodchklist: []
};
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length + " checkboxes are checked";
result.each(function(){
resultstring += $(this).val();
}
// add this
data.prodchklist.push($(this).val());
}
Then during ajax call:
$.post('second.php', data, function(response) {
....
});
In your second PHP file, just retrieve it as usual, eg:
$selectedProducts = $_POST['prodchklist'];
This works for both approach (without javascript and with ajax).
$selectedProducts will be an array instead of simple string value. Just iterate the array to use the values, eg:
foreach ($selectedProducts as $product) {
echo $product;
}
Just wanted to know if any of you had any code (JQuery, AJAX, etc) to add a new row to a table that has some dropdown lists in some columns... I was able to add a new row by adding some javascript and jquery, but for some reason (it was working before, but suddenly stopped and I cannot recall the last changes I made to be honest) it's not working anymore. First, I made PHP functions to retrieve the contents for the dropdowns from a DB. Then I added the HTML code in a java script function ("Addnewrow()") to add the new rows and include the dropdowns in specific columns. Thing is, rows are only added when I remove the lines in the "Addnewrow()" function that contains the PHP function ("creaLista"). I have tried changing the Jquery versions, removing all bootstrap files and so, but nothing works. I also tried different combinations in those lines of single and double quotes. I also removed the non-essential code, such as the "Render" section for the selectpicker
Here's the javascript section:
function addnewrow()
{
$('.selectpicker').selectpicker('render');
var n = ($('.detail tr').length-0)+1;
var tr = "<tr>" +
'<td class="no">' + n + '</td>'+
"<td><?php creaLista('mrditemid[]',3,'SPARES_ID','SPARES_BRIEFDESC',$query2, $m);?></td>"+
"<td><?php creaLista('mrdunits[]',4,'UNIT_ID','UNIT_DESC',$query2, $m);?></td>"+
'<td><input type="text" class="form-control mrdquantity" name="mrdquantity[]"></td>'+
'<td><input type="text" class="form-control mrdremarks" name="mrdremarks[]"></td>'+
'<td><button class="btnDelete btn btn-danger">-</td>'+
'</tr>';
$('.detail').append(tr);
}
I may add that the first row is generated automaticaly in HTML, also calling the same function "crealista" and it works fine. Now, when I click on the button that triggers the "Addrow()" function it simply does nothing, and when I remove the lines containing the "Crealista" function it does work, so it has to do with how the var "tr" is being read, I believe...
Thanks in advance for any insights on this!
> function CopyRow(e) {
> var r = confirm("Do you want to Copy this record?");
> if (r == true) {
>
> var $tr = $(e).closest('tr');
> var $clone = $tr.clone();
> var lastRow = $tr.clone();
>
> lastRow.find('select').each(function (idx, el) {
> var $el = $(el);
> $el.val($tr.find('select').eq(idx).val())
> });
> $tr.after(lastRow);
>
>
> }
>
> else {
> return false;
> }
> }
It will add new row and will also copy the previous row.
You can not use PHP inside JS like how you are using. For achieve your goal you need to use AJAX terminology.
Now how you will use? See the below code.
Consider you have misc.js file. (misc.js is just random name).
function addnewrow()
{
$('.selectpicker').selectpicker('render');
var n = ($('.detail tr').length-0)+1;
// Make Ajax Call
$.get( "ajax/get-next-row.php", { row: n }, function( tr ) {
$('.detail').append(tr);
});
}
get-next-row.php
/* ---------- Get row query parameter from AJAX GET ---------- */
$n = $_GET['row'];
/* =============================================
= Section : Table row logic =
============================================= */
// Write here your row logic and pass it to tr.
// E.g:
define('SPARES_ID', 'xxx');
define('SPARES_BRIEFDESC', 'xxx');
define('UNIT_ID', 'xxx');
define('UNIT_DESC', 'xxx');
$query2 = '';
$m = '';
/* ===== End of Section ====== */
/* ---------- Generate Table Row and return it---------- */
echo $tr = '<tr> '
. '<td class="no">' . $n . '</td>'
. '<td>' . creaLista('mrditemid[]', 3, SPARES_ID, SPARES_BRIEFDESC, $query2, $m) . '</td>'
. '<td>' . creaLista('mrdunits[]', 4, UNIT_ID, UNIT_DESC, $query2, $m) . '</td>'
. '<td><input type="text" class="form-control mrdquantity" name="mrdquantity[]"></td>'
. '<td><input type="text" class="form-control mrdremarks" name="mrdremarks[]"></td>'
. '<td><button class="btnDelete btn btn-danger">-</td>'
. '</tr>';
exit();