I'm trying to get first cell (td) for each row and getting it but only for current page. If I navigate to next page then the checkbox checked on the previous page is not being sent.
<table class="table" id="example2">
<thead><tr>
<th>Roll no</th><th>Name</th></tr><thead>
<?php
$sel = "SELECT * FROM `st`";
$r = mysqli_query($dbc, $sel);
while ($fet = mysqli_fetch_array($r)) {
?>
<tr>
<td><?php echo $fet['trk'] ?></td>
<td><input type="text" value="<?php echo $fet['ma'] ?>" id="man" class="form-control"></td>
<td><input type="checkbox" id="check" name="myCheckbox" class="theClass"></td></tr>
<?php } ?>
</table>
<input type="submit" id="sub_marks" class="btn btn-info" value="Submit & Continue">
<script src="plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
})
});
</script>
<script>
$('#sub_marks').click(function () {
var values = $("table #check:checked").map(function () {
return $(this).closest("tr").find("td:first").text();
}).get();
alert(values);
})
</script>
CAUSE
jQuery DataTables removes non-visible rows from DOM for performance reasons. When form is submitted, only data for visible checkboxes is sent to the server.
SOLUTION 1. Submit form
You need to turn elements <input type="checkbox"> that are checked and don't exist in DOM into <input type="hidden"> upon form submission.
var table = $('#example').DataTable({
// ... skipped ...
});
$('form').on('submit', function(e){
var $form = $(this);
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
SOLUTION 2: Send data via Ajax
var table = $('#example').DataTable({
// ... skipped ...
});
$('#btn-submit').on('click', function(e){
e.preventDefault();
var data = table.$('input[type="checkbox"]').serializeArray();
// Include extra data if necessary
// data.push({'name': 'extra_param', 'value': 'extra_value'});
$.ajax({
url: '/path/to/your/script.php',
data: data
}).done(function(response){
console.log('Response', response);
});
});
DEMO
See jQuery DataTables: How to submit all pages form data for more details and demonstration.
NOTES
Each checkbox should have a value attribute assigned with unique value.
Avoid using id attribute check for multiple elements, this attribute is supposed to be unique.
You don't need to explicitly enable paging, info, etc. options for jQuery DataTables, these are enabled by default.
Consider using htmlspecialchars() function to properly encode HTML entities. For example, <?php echo htmlspecialchars($fet['trk']); ?>.
You do not have to make hidden element on form just before submit simply destroy data table before submit and it will submit all checkbox on all pages like normal
$('form').on('submit', function (e) {
$('.datatable').DataTable().destroy();
});
<form action="Nomination" name="form">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables- example">
<tbody>
<%while (rs1.next()){%>
<tr>
<td><input type="checkbox" name="aabb" value="<%=rs1.getString(1)%>" /></td>
</tr>
<%}%>
</tbody>
</table>
</form>
and add script with correct form id and table id
<script>
var table = $('#dataTables-example').DataTable({
// ... skipped ...
});
</script>
<script>
$('form').on('submit', function(e){
var $form = $(this);
table.$('input[type="checkbox"]').each(function(){
if(!$.contains(document, this)){
if(this.checked){
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);} } }); });
</script>
This is working code
Great code from Gyrocode.com, but if you have some other hidden values in your rows, you will have to create them too in the form.
I use :
var table = $('#example').DataTable({
// ... skipped ...
});
$("#buttonValidation").click(function(){
table.page.len(-1).draw();
});
It just displays on screen all the datatable without pagination before sending it in the form. Maybe if you want to hide the display, you can use css opacity :0 (but not display:none).
Related
var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
tb.row.add([typeName, amount]).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
</tr>
</thead>
</table>
i need to append edit and delete button for every row. when click the edit button, row data should load to dropdown and textbox. can u guide me to do this ?
With certain changes to the architecture of your app, I would suggest the following approach that employs native DataTables options and API methods:
//initialize DataTable
const tb = $('#example').DataTable({
//remove non-essential controls for the sake of cleaner view
dom: 't',
//use columns option to setup header titles
columns: [
{title: 'Type'},
{
title: 'Amount',
//user 'render' to append Edit/Delete buttons for each entry
render: data => `${data}<button action="delete">Delete</button><button action="edit">Edit</button>`
}
]
});
//click handler for dual purpose 'Submit' button that adds new rows and submits edits
$('#submit').on('click', function() {
//when submit button acts to append new row to the table (default)
if($(this).attr('action') == 'addRow'){
tb.row.add([$("#type").val(), $("#amount").val()]).draw();
}
//when submit button acts to submit edits
if($(this).attr('action') == 'confirmEdit'){
//change affected row data and re-draw the table
tb.row($(this).attr('rowindex')).data([$("#type").val(), $("#amount").val()]).draw();
}
//clean up form, switch it to default state
$('#type').val("");
$('#amount').val("");
$('#submit').attr('action', 'addRow');
});
//'Delete' button click handler
$('#example').on('click', 'tbody tr button[action="delete"]', function(event){
tb.row($(event.target).closest('tr')).remove().draw();
});
//'Edit' button click handler
$('#example').on('click', 'tbody tr button[action="edit"]', function(){
//get affected row entry
const row = tb.row($(event.target).closest('tr'));
//get affected row().index() and append that to 'Submit' button attributes
//you may use global variable for that purpose if you prefer
$('#submit').attr('rowindex', row.index());
//switch 'Submit' button role to 'confirmEdit'
$('#submit').attr('action', 'confirmEdit');
//set up 'Type' and 'Amount' values according to the selected entry
$('#type').val(row.data()[0]);
$('#amount').val(row.data()[1]);
});
tbody tr button {
display: block;
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<label>Type</label>
<select id="type">
<option value="" selected></option>
<option value="Type 01">Type 01</option>
<option value="Type 02">Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="submit" action="addRow">Submit</button>
<table id="example" class="display" cellspacing="0" width="100%"></table>
Add your HTML directly. I've added button, you can similarly add a drop down too. Consider the following:
var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
var row = tb.row.add([typeName, amount, "<span><button>Edit</button><button>Delete</button></span>"]).draw();
var edit = row.node().getElementsByTagName("button")[0];
edit.onclick = function() {
document.getElementById('typeEdit').value = row.data()[0];
document.getElementById('amtEdit').value = row.data()[1];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<br/ >
<br/ >
Edit Type
<select id="typeEdit">
<option> Type 01</option>
<option> Type 02</option>
</select>
Edit Amount
<input id="amtEdit" />
<br/ >
<br/ >
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Ops</th>
</tr>
</thead>
</table>
RowEditor.js
I had a similiar issue and wrote a tiny JS tool, that targets editing of rows inline. The repo can be found here. I think its functionality is best described by the picture below, but you can also find a running example here.
Setting it up
What you have to do to integrate it, is
Download and integrate the file
<script type="text/javascript" charset="utf8" src="/js/RowEditor.js"></script>
Set up a configuration about which columns shall be editable and if they should be editable as dropdown or input (compare it to the example picture, you will quickly figure out what it does):
"1":{"type":"input"},
"2":{"type":"input"},
"3":{"type":"select",
"options":{
"1":{"value":'Sales Assistant', "title":'Sales Assistant'},
"2":{"value":'Tech Lead', "title":'Tech Lead'},
"3":{"value":'Secretary', "title":'Secretary'},
"4":{"value":'Developer', "title":'Developer'},
"5":{"value":'Trainee', "title":'Trainee'}
}
}
}
Call the editor, after you have initialized your DataTable:
$(document).ready( function () {
table = $('#table').DataTable();
rowEditor = new RowEditor('#table', table, editRowSettings);
});
Call the function editRow of rowEditor (or however you have named it above) with the index of the row you want to edit. I have the button placed in a sepperate column of the datatable, but you can call it anyway you want it.
<button onclick="rowEditor.editRow(1)">Edit</button>
If you have questions, feel free to ask or issue a pull request :)
I'm trying to get first cell (td) for each row and getting it but only for current page. If I navigate to next page then the checkbox checked on the previous page is not being sent.
<table class="table" id="example2">
<thead><tr>
<th>Roll no</th><th>Name</th></tr><thead>
<?php
$sel = "SELECT * FROM `st`";
$r = mysqli_query($dbc, $sel);
while ($fet = mysqli_fetch_array($r)) {
?>
<tr>
<td><?php echo $fet['trk'] ?></td>
<td><input type="text" value="<?php echo $fet['ma'] ?>" id="man" class="form-control"></td>
<td><input type="checkbox" id="check" name="myCheckbox" class="theClass"></td></tr>
<?php } ?>
</table>
<input type="submit" id="sub_marks" class="btn btn-info" value="Submit & Continue">
<script src="plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
})
});
</script>
<script>
$('#sub_marks').click(function () {
var values = $("table #check:checked").map(function () {
return $(this).closest("tr").find("td:first").text();
}).get();
alert(values);
})
</script>
CAUSE
jQuery DataTables removes non-visible rows from DOM for performance reasons. When form is submitted, only data for visible checkboxes is sent to the server.
SOLUTION 1. Submit form
You need to turn elements <input type="checkbox"> that are checked and don't exist in DOM into <input type="hidden"> upon form submission.
var table = $('#example').DataTable({
// ... skipped ...
});
$('form').on('submit', function(e){
var $form = $(this);
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
SOLUTION 2: Send data via Ajax
var table = $('#example').DataTable({
// ... skipped ...
});
$('#btn-submit').on('click', function(e){
e.preventDefault();
var data = table.$('input[type="checkbox"]').serializeArray();
// Include extra data if necessary
// data.push({'name': 'extra_param', 'value': 'extra_value'});
$.ajax({
url: '/path/to/your/script.php',
data: data
}).done(function(response){
console.log('Response', response);
});
});
DEMO
See jQuery DataTables: How to submit all pages form data for more details and demonstration.
NOTES
Each checkbox should have a value attribute assigned with unique value.
Avoid using id attribute check for multiple elements, this attribute is supposed to be unique.
You don't need to explicitly enable paging, info, etc. options for jQuery DataTables, these are enabled by default.
Consider using htmlspecialchars() function to properly encode HTML entities. For example, <?php echo htmlspecialchars($fet['trk']); ?>.
You do not have to make hidden element on form just before submit simply destroy data table before submit and it will submit all checkbox on all pages like normal
$('form').on('submit', function (e) {
$('.datatable').DataTable().destroy();
});
<form action="Nomination" name="form">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables- example">
<tbody>
<%while (rs1.next()){%>
<tr>
<td><input type="checkbox" name="aabb" value="<%=rs1.getString(1)%>" /></td>
</tr>
<%}%>
</tbody>
</table>
</form>
and add script with correct form id and table id
<script>
var table = $('#dataTables-example').DataTable({
// ... skipped ...
});
</script>
<script>
$('form').on('submit', function(e){
var $form = $(this);
table.$('input[type="checkbox"]').each(function(){
if(!$.contains(document, this)){
if(this.checked){
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);} } }); });
</script>
This is working code
Great code from Gyrocode.com, but if you have some other hidden values in your rows, you will have to create them too in the form.
I use :
var table = $('#example').DataTable({
// ... skipped ...
});
$("#buttonValidation").click(function(){
table.page.len(-1).draw();
});
It just displays on screen all the datatable without pagination before sending it in the form. Maybe if you want to hide the display, you can use css opacity :0 (but not display:none).
I am using jQuery DataTables I implement multiple selection of users in a table. My problem is how to add or append the selected checkbox in a row into the $(form).serialize() before submitting? And how to do console.log the data selected checkbox in row?
I use this following library:
https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.7/js/dataTables.checkboxes.js
https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.7/css/dataTables.checkboxes.css
DataTables jQuery Configuration:
$(document).ready(function() {
var usersTable = $("#users-table").DataTable({
ajax: {
url: GetBaseUrl() + URL_USER_LIST,
type: "GET",
dataSrc: function(data) {
return data;
}
},
responsive: true,
lengthMenu: [10, 25, 50, 75, 100],
bPaginate: true,
bFilter: false,
bInfo: false,
bLengthChange: false,
bAutoWidth: false,
columnDefs: [
{
targets: 0,
data: null,
defaultContent: "",
orderable: false,
className: "select-checkbox",
checkboxes: {
seletRow: true
}
},
{
targets: 1,
data: "FullName",
orderable: false,
render: function(data) {
return data;
}
},
{
targets: 2,
data: "EmailAddress",
orderable: false,
render: function(data) {
return data;
}
}
],
select: {
style: "multi"
},
order: [[1, "asc"]]
});
$(document).on("click",
"button",
function(e) {
e.preventDefault();
const result = $('input[type="checkbox"]:checked', usersTable.rows().nodes()).map(
function() {
return this.value;
}).get();
console.log(result);
});
});
HTML:
<div class="form-group">
<table id="users-table" class="table-hover table-bordered table-striped table-responsive display select" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tfoot>
</tfoot>
</table>
</div>
SUBMIT:
$(container).on(eventClick,
btnClassSave,
function(e) {
e.preventDefault();
window.common._save(container,
GetBaseUrl() + URL_SAVE,
$(".users-form").serialize(),
"listview",
widget._saveSuccess);
});
<button class="btn btn-success save-button">
<span class="glyphicon glyphicon-floppy-disk"></span> Save
</button>
<button class="btn btn-default cancel-button" data-dismiss="modal">
<span class="glyphicon glyphicon-remove"></span> Cancel
</button>
if you're in .NET, ensure that you have the name attribute of the checkbox set to the property you want to bind to.
Since the output of .serialize() is just a url encoded string, You could append to the serialize like this;
var data = $(".users-form").serialize()+"&checkbox1=VALUE"+"&checkbox2=VALUE";
Try the snippet below.
$("form").submit(function(e) {
e.preventDefault();
// store form values to variable data
var data = $("form").serialize();
// loop through checked checkboxes
$(".input-checkbox:checked").each(function() {
// append its value to variable data
data += "&" + $(this).attr("name") + "=" + $(this).val();
});
// show serialized string
console.log(data);
});
table {
margin-top: 20px;
border: 1px solid grey;
border-collapse: collapse;
}
table tr th {
border-bottom: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="name" />
<input name="email" />
<button type="submit">Submit</button>
</form>
<table>
<thead>
<tr>
<th>Checkbox 1</th>
<th>Checkbox 2</th>
<th>Checkbox 3</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="checkbox1" type="checkbox" class="input-checkbox" value="test1" /></td>
<td><input name="checkbox2" type="checkbox" class="input-checkbox" value="test2" /></td>
<td><input name="checkbox3" type="checkbox" class="input-checkbox" value="test3" /></td>
</tr>
</tbody>
</table>
To console log the row data, I think you could use .parent() or .parents("tr");
$("input[type="checkbox"]:checked").each(function(){
// the first .parent() is to navigate to the TD
// the second .parent() is to navigate to the TR
console.log($("this").parent().parent());
// show the html content of the second column;
console.log($("this").parent().parent().find("td").eq(1).html());
});
nice! but how to console the row data if you click the checkbox in a row? thanks
The SUBMIT code snippet you have provided, you have
$(".users-form").serialize()
so you are serializing all form data and performing submit.
var data = $(".users-form").serialize() + "&checkBoxId=" + checkBoxValue;
This will append checkbox value to form data, Use the data to post your form value, as shown below.
var data = $(".users-form").serialize() + "&checkBoxId=" + checkBoxValue;
$(container).on(eventClick,
btnClassSave,
function(e) {
e.preventDefault();
window.common._save(container,
GetBaseUrl() + URL_SAVE,
data,
"listview",
widget._saveSuccess);
});
Try this implementation that serializes datatable form data.
$(document).ready(function (){
var table = $('#example1').DataTable({
pageLength: 4
});
// Handle form submission event
$('#frm-example1').on('submit', function(e){
var form = this;
// Encode a set of form elements from all pages as an array of names and values
var params = table.$('input,select,textarea').serializeArray();
// Iterate over all form elements
$.each(params, function(){
// If element doesn't exist in DOM
if(!$.contains(document, form[this.name])){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
});
});
});
For more info refer this.
https://www.gyrocode.com/articles/jquery-datatables-how-to-submit-all-pages-form-data/
I have HTML table with dynamically generated contents. A td in the table contains a form. What I want is to remove the table from the page once this form is submitted because another page will be included at form submitting. I am using ajax and php. How can I amend my code below to remove the table once the form is submitted?
JAVASCRIPT
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
}
});
$('#forms').click(function(){
$('#table').hide();
});
return false;
}
HTML
<div id="msg"></div>
<div id="table">
<table align="center">
<tbody>
<tr>
<th>S/N</th>
<th>Subject</th>
<th>Edit</th>
</tr>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $subject;?></td>
<td>
<form id="myform">
<input type="text" id="name-<?php echo $item_id;?>" hidden name="name" value="<?php echo $item_id;?>" >
<button type="submit" id="forms" onclick="return chk(<?php echo $item_id;?>)">Edit</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
$('#forms').click(function(){
$('#table').hide();
});
At the moment, when the form submits, the above code means you're creating an event handler to listen for the next time the button is clicked, which would then hide the table at that time.
To hide it as soon as the form is submitted, then simply remove the event handler part and just write
$('#table').hide();
by itself within the "chk" function.
N.B. If you don't want it to hide until after the ajax call is completed successfully, then move it inside the "success" function.
According to your question title:
You can simply add these lines in your ajax success: :
$("#table table").remove();
OR
You can set innerHTML of div to empty
$("#table").html("");
I hope this should work.
why do you need a <form> tag anyway? a more simple approach which doesn't involve jQuery
HTML
<input name="" />
<button id="submit">Submit</button>
JS
submit.onclick = function(){
element = document.querySelector('holderClass');
element.style.display = 'none'; // or any element
// ...ajax here
}
you might need document.querySelector()
//In success block you can remove the table by using $('#table').html("");
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
$('#table').html("");
}
});
return false;
}
I have been using bootstrap tables to fetch data from database using kendo datasource. So in order to make it more interactive i have used a checkbox for simultaneous actions.
I want to delete all the entries with one checkbox. I have read about deleting entries with single checkbox using jQuery. But problem is that I have only one checkbox in table and all the entries are being fetched using kendo data source.
If i am creating confusion then see here-
<script id="template" type="text/x-kendo-template">
<tr>
<td>
<input type="checkbox" class="done" data-id="#= CID #" ></input>
</td></tr>
</script>
<table>
<tr>
<th style="width:10%;">
<input type="checkbox" />
</th>
</tr>
</table>
Now with using kendo datasource i have one column of checkboxes only.
So i am doing this-
<script type="text/javascript">
$('.done').click(function (event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
}
});
</script>
And still no result. Help!
Try to wrap your jQuery code inside $(document).ready(function(){}); or $(function(){}); to let it see the whole DOM:
$(document).ready(function() {
$('.done').click(function (event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
}
});
});
Also, your HTML are wrapped inside the script tag, move it outside and remove redundant ' as well as the input tag doesn't need a closing </input> tag:
<tr>
<td>
<input type="checkbox" class="done" data-id="#= CID #" />
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$('.done').click(function (event) {
if ($(this).attr('checked')) {
$('input:checkbox:not(".done")').each(function () {
$(this).attr('checked', 'checked');
});
}
});
});
</script>
Try this. it may works
Try this:
$(function () {
$('.done').on('click', function(){
// i comment this condition if you want selectall for checked or unchecked
//if ($(this).is(':checked')){
$(':checkbox').prop('checked', this.checked);
//}
});
});
Just try this:
Script
$(document).ready(function(){
$('.done').click(function (event) {
$('.chkbxq').each(function () {
$(this).attr('checked', flag);
});
});
});
HTML:
<table>
<tr>
<th style="width:10%;">
<input type="checkbox" class="chkbxq" />
</th>
</tr>
</table>