Submitting form resubmits the same data - javascript

I'm having some problems with a table that I created using a Gyrocode example. I modified it to fetch and submit data via ajax and to leverage Datatables server side processing.
Basically what is happening is I can select row1 and submit the form and everything works fine. I then de-select row1 and select row2 and when I submit, it will submit for row1 & row2.
I have created a JSFiddle to replicate and am logging the form variable to the console.
Step1: Selected row1 and clicked 'Request Selected' button, here is the output
<form id="frm-example">
<div class="table-responsive">...</div>
<input type="hidden" name="id[]" value="1">
</form>
Step2: Did not refresh page, de-selected row1, selected row2 and clicked 'Request Selected' button, here is the output. You can see the first row is still in the variable.
<form id="frm-example">
<div class="table-responsive">...</div>
<input type="hidden" name="id[]" value="1">
<input type="hidden" name="id[]" value="2">
</form>
I tried clearing the form variable when a request was successfully posted but it seems to come back. I'm not sure how to deselect everything and reset the variables back to null when a request was already submitted.
HTML:
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12">
<!-- /.panel-heading -->
<div class="panel-body">
<form id="frm-example">
<div class="table-responsive">
<div class="row">
<div class="col-lg-12" style="padding-bottom: 5px;">
<button id="btn-submit" class="btn btn-success" disabled><i class="fa fa-floppy-o"></i> Request Selected (0)</button>
</div>
</div>
<div class="table-responsive">
<table class="display select table table-striped table-bordered table-hover" id="example">
<thead>
<tr>
<th>
<input name="select_all" value="1" type="checkbox">
</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript:
//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table) {
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
// If none of the checkboxes are checked
if ($chkbox_checked.length === 0) {
chkbox_select_all.checked = false;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length) {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = true;
}
}
}
$(document).ready(function() {
// Array holding selected row IDs
var rows_selected = [];
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'sAjaxSource': 'data.php',
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'width': '1%',
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
return '<input type="checkbox">';
}
}],
'order': [
[1, 'asc']
],
'rowCallback': function(row, data, dataIndex) {
// Get row ID
var rowId = data[0];
// If row ID is in the list of selected row IDs
if ($.inArray(rowId, rows_selected) !== -1) {
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}
});
setInterval(function test() {
table.ajax.reload(null, false); // user paging is not reset on reload
$(".dataTables_processing").hide();
}, 2000);
// Handle click on checkbox
$('#example tbody').on('click', 'input[type="checkbox"]', function(e) {
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);
// If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}
if (this.checked) {
$row.addClass('selected');
document.getElementById("btn-submit").innerHTML = '<i class="fa fa-floppy-o"></i>' + " Request Selected (" + rows_selected.length + ")";
} else {
$row.removeClass('selected');
document.getElementById("btn-submit").innerHTML = '<i class="fa fa-floppy-o"></i>' + " Request Selected (" + rows_selected.length + ")";
}
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
$('#btn-submit').prop('disabled', (!rows_selected.length));
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle click on table cells with checkboxes
$('#example').on('click', 'tbody td, thead th:first-child', function(e) {
$(this).parent().find('input[type="checkbox"]').trigger('click');
});
// Handle click on "Select all" control
$('thead input[name="select_all"]', table.table().container()).on('click', function(e) {
if (this.checked) {
$('#example tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#example tbody input[type="checkbox"]:checked').trigger('click');
}
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle table draw event
table.on('draw', function() {
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});
// Handle form submission event
$('#frm-example').on('submit', function(e) {
if (!e.isDefaultPrevented()) {
var url = "process.php";
var form = this;
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId) {
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
console.log(form);
}
});
return false;
}
})
});

I just figured it out! I ended up iterating back over the selected rows and removing the elements from the form variable after I get a success back from ajax.
$('#frm-example').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "process.php";
form = this;
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
$.each(rows_selected, function(index, rowId){
// Remove hidden element
$(form).children("input").remove();
});
}
});
return false;
}
})

Related

Deleting multiple rows of a table with Jquery and ajax

I want to be able to delete checkbox-selected rows but when I click on "Delete Selected", both the table on the web page and MySQL database stay unchanged. How do I get the selected rows from both the web page and the database to be deleted?
Edit: I'm now able to delete the rows but only the first row, despite selecting more than one checkbox, or selecting another checkbox not on the first row. Also, if I want to delete another entry, I will have to first refresh the page before deleting another one.
datatable.php
<div class="row well">
<a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>
<script type="text/javascript">
$(document).ready(function($)
{
function create_html_table (tbl_data) {
tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';
tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';
tbl +='<tbody>';
$.each(tbl_data, function(index, val)
{
var row_id = val['row_id'];
//loop through ajax row data
tbl +='<tr id="row" row_id="'+row_id+'">';
tbl +='<td><input type="checkbox" class="sub_chk"></td>';
tbl +='<td>'+(index + 1)+'</td>';
tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
// More data
tbl +='</tr>';
});
tbl +='</tbody>';
tbl +='</table>';
}
var ajax_url = "<?php echo APPURL;?>/ajax.php" ;
// Multi-select
$(document).on("click","#master", function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
var ele_this = $('#row') ;
var row_id = ele_this.attr('row_id');
var allVals = [];
$(".sub_chk:checked").each(function()
{
allVals.push(row_id);
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var data_obj=
{
call_type:'delete_row_entry',
row_id:row_id,
};
ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
}
else if(d1.status == "success")
{
ele_this.closest('tr').css('background','red').slideUp('slow');
}
});
}
});
});
</script>
ajax.php
//--->Delete row entry > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")
{
$row_id = app_db()->CleanDBData($_POST['row_id']);
$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0)
{
//found a row to be deleted
$strTableName = "data";
$array_where = array('row_id' => $row_id);
//Call it like this:
app_db()->Delete($strTableName,$array_where);
echo json_encode(array(
'status' => 'success',
'msg' => 'deleted entry',
));
die();
}
}
//--->Delete row entry > end
I've seen other similar SO questions like this one but I don't think it is applicable to my code.
My output:
To achieve what you want, you have to select the good elements the right way. For example, an HTML id must be unique, so giving all your elements the same id="row" won't work. Using your class will be enough. Then you have to consider that each will execute the function separately for all your selected elements, so that if you want to do things for each element, all the code must be inside.
I optimized a little your code by getting rid of allVals variable, if its only goal is to test if rows have been selected, you can directly test .length on your selection. I renamed variables so that it's more clear which is what.
Also it's not very clear in the question if the "Please wait....deleting your entry" text should appear in the button or in each row, i assumed it was in the button, and it will help you differentiate all elements from how they are selected.
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
//'click' is called on the button, so 'this' here will be the button
var button = $(this) ;
var checked_checkboxes = $(".sub_chk:checked");
if(checked_checkboxes.length <=0)
{
alert("Please select row.");
}
else {
button.html('<p class="bg-warning">Please wait....deleting your entry</p>');
//next code will be executed for each checkbox selected:
checked_checkboxes.each(function(){
var checkbox = $(this);
var row_id = checkbox.attr('row_id');
var data_obj=
{
call_type: 'delete_row_entry',
row_id: row_id,
};
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
//you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
}
else if(d1.status == "success")
{
checkbox.closest('tr').css('background','red').slideUp('slow');
}
});
});
}
});

Validate at least one auto generate jquery datatable checkbox is checked using MVC

Trying to make sure the user select at least one check box before submitting the form. At the moment my JavaScript is not working. The checkbox is auto generate in the jquery datatable. The code is still getting to the controller even when none of the checkbox in the table is not selected
HTML
<table id="scheduleAppointment-data-table" class="table table-striped table- bordered" style="width:100%;"></table>
<input type="submit" value="Send" class="btn btn-default" id=btnSubmit onclick="Validate()"/>
Datatable
// Auto generate checkbox
"columns": [
{
targets": [0],
"data": "EDMXID", "autoWidth": true,
"render": function (data, type, full) {
return '<input type="checkbox" id="EDMXID" name="EDMXID" value="'+full.EDMXID+'"/>';
},
}]
Javascript
function Validate() {
var allOk = true;
$(scheduleAppointment-data-table).find("tbody tr").each(function (){
var row = $(this);
var checked = row.find($(':checkbox:checked')).length > 0
if (!checked) {
allOk = false;
alert('At least One Appointment Should Be Selected');
return allOk;
}
});
return allOk;
}
With help from Davidkonrad comment I finally used the JavaScript code below
$(function () {
$('input[id$=btnSubmit]').click(function (e) {
$('#scheduleAppointment-data-table').find("tbody tr").each(function () {
var row = $(this);
var checked = row.find($(':checkbox:checked')).length > 0
if (!checked) {
alert('At least One Appointment Should Be Selected');
e.preventDefault();
}
});
});
});

Jquery Datatable drag and drop a column from one table to another

I am using: jquery.dataTables.js from: https://datatables.net
I am trying to drag and drop a column from one table to another.
EDIT:
so basically what I want to do is:
be able to drag and drop the names from table 2 into column called name in the table above
after drag and drop the name the same should disappear from the table 2.
case 2: if I add a new row using the button Add new Row
I need be able to drag a drop the names from table 2 into that column name too.
so basically I want to do a drag and drop just in the column not in the row.
I don't want create a new row just move the names from 1 table to another.
EDIT 2:
1- Can you drag/drop multiples values from Table #2 to Table #1?
no, the drag and drop will be possible just 1 by 1.
The drag and drop will be just possible after the user clicks in edit or add a new row.
so I will be able to replace names drom table 2 into the column names table 1
2- If no, the value dragged shall then replace the value where it is dropped?
yes
3- If yes,how should it work? Adding new rows with the other values blank?
no row need be added, we just need replace the column name.
how will works:
so after click in edit or add new row i will be able to drag a name from table 2 into column in
table 1.
few more resquests:
if select the row in table 2, this row should be change the color, showing was selected. and in the table 1 column name where this need be dropped need to change the color to show the user can be dropped, after the user drop the color should back to normal.
sample working here:
http://plnkr.co/edit/6sbmBzbXDzm4p6CjaVK0?p=preview
$(document).ready(function() {
var dataUrl = 'http://www.json-generator.com/api/json/get/ccTtqmPbkO?indent=2';
var options = [
{ key : 'option 1', value : 1 },
{ key : 'option 2', value : 2 },
{ key : 'option 3', value : 3 }
];
$(document).ready(function() {
var $table = $('#example');
var dataTable = null;
$table.on('mousedown', 'td .fa.fa-minus-square', function(e) {
dataTable.row($(this).closest("tr")).remove().draw();
});
$table.on('mousedown.edit', 'i.fa.fa-pencil-square', function(e) {
enableRowEdit($(this));
});
$table.on('mousedown', 'input', function(e) {
e.stopPropagation();
});
$table.on('mousedown.save', 'i.fa.fa-envelope-o', function(e) {
updateRow($(this), true); // Pass save button to function.
});
$table.on('mousedown', '.select-basic', function(e) {
e.stopPropagation();
});
dataTable = $table.DataTable({
ajax: dataUrl,
rowReorder: {
dataSrc: 'order',
selector: 'tr'
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}, {
data: 'delete'
}]
});
$table.css('border-bottom', 'none')
.after($('<div>').addClass('addRow')
.append($('<button>').attr('id', 'addRow').text('Add New Row')));
// Add row
$('#addRow').click(function() {
var $row = $("#new-row-template").find('tr').clone();
dataTable.row.add($row).draw();
// Toggle edit mode upon creation.
enableRowEdit($table.find('tbody tr:last-child td i.fa.fa-pencil-square'));
});
$('#btn-save').on('click', function() {
updateRows(true); // Update all edited rows
});
$('#btn-cancel').on('click', function() {
updateRows(false); // Revert all edited rows
});
function enableRowEdit($editButton) {
$editButton.removeClass().addClass("fa fa-envelope-o");
var $row = $editButton.closest("tr").off("mousedown");
$row.find("td").not(':first').not(':last').each(function(i, el) {
enableEditText($(this))
});
$row.find('td:first').each(function(i, el) {
enableEditSelect($(this))
});
}
function enableEditText($cell) {
var txt = $cell.text();
$cell.empty().append($('<input>', {
type : 'text',
value : txt
}).data('original-text', txt));
}
function enableEditSelect($cell) {
var txt = $cell.text();
$cell.empty().append($('<select>', {
class : 'select-basic'
}).append(options.map(function(option) {
return $('<option>', {
text : option.key,
value : option.value
})
})).data('original-value', txt));
}
function updateRows(commit) {
$table.find('tbody tr td i.fa.fa-envelope-o').each(function(index, button) {
updateRow($(button), commit);
});
}
function updateRow($saveButton, commit) {
$saveButton.removeClass().addClass('fa fa-pencil-square');
var $row = $saveButton.closest("tr");
$row.find('td').not(':first').not(':last').each(function(i, el) {
var $input = $(this).find('input');
$(this).text(commit ? $input.val() : $input.data('original-text'));
});
$row.find('td:first').each(function(i, el) {
var $input = $(this).find('select');
$(this).text(commit ? $input.val() : $input.data('original-value'));
});
}
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/bXcKDeAbyq?indent=2';
table = $('#example2').DataTable({
ajax: url,
order: [[ 0, "desc" ]],
rowReorder: {
dataSrc: 'place',
selector: 'tr'
},
columns: [ {
data: 'name'
}]
});
});
});
div.addRow {
line-height: 45px;
background-color: #fff;
padding-left: 10px;
border-bottom: 1px solid;
border-top: 1px solid #e5e5e5;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="//cdn.rawgit.com/DataTables/RowReorder/ce6d240e/js/dataTables.rowReorder.js"></script>
<link href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="//cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
<th>action</th>
</tr>
</thead>
</table>
<table id="new-row-template" style="display:none">
<tbody>
<tr>
<td>999</td> <!-- Use a large number or row might be inserted in the middle -->
<td>__NAME__</td>
<td>__COUNTRY__</td>
<td>
<i class="fa fa-pencil-square" aria-hidden="true"></i>
<i class="fa fa-minus-square" aria-hidden="true"></i>
</td>
</tr>
</tbody>
</table>
<br>
<div class="pull-right">
<button type="button" id="btn-cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btn-save" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
I've already responded to this question here: How to drag and drop a column into another
Some changes to your code (a global MouseUp event and a MouseDown event for the second table):
var rowChache = [];
function mouseUp(event) {
var ctrl = $(document.elementsFromPoint(event.clientX, event.clientY)).filter('input.border-highlight');
if (ctrl.length > 0 && rowCache.length > 0) {
var el = rowCache[0];
var data = el.row.data();
if (data.length > 0) {
ctrl.val(data[0].name);
el.row.remove().draw();
}
}
rowCache = [];
$('#example tr td:nth-child(2) input').removeClass('border-highlight');
}
table.on('mousedown', 'tbody tr', function() {
var $row = $(this);
var r = table.rows(function(i, data) {
return data.name == $row.children().first().text();
});
if (r[0].length > 0) {
$row.parents('table').find('tr').removeClass('highlight');
$row.addClass('highlight');
$('#example tr td:nth-child(2) input').addClass('border-highlight');
}
rowCache.push({
row: r
});
});
Check also the link: http://jsfiddle.net/f7debwj2/47/
Did you even try searching?
https://datatables.net/forums/discussion/30197/add-remove-table-rows-on-drag-and-drop-between-two-datatables
move rows between two datatables
https://gist.github.com/davemo/706167
drag n drop between two tables
Drag/drop between two datatables
The most important tidbit comes from the creator of datatables:
This is not a feature of DataTables, however, it should be quite possible using the API. Specifically I would suggest using row().remove() and row.add() to remove and add rows as required. The drag and drop code however would be external to DataTables.
You will either use https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API or do something in JS, and/or write the missing functionality into the API, but given the above links, you'll see how people have tackled the same problem you've described. Instead of rows, you'll do columns and I'm sure it can all be modified to do exactly what you want.
This one looks like similar to:
How to drag and drop a column into another
I have commented on the above post. See If you wanna take that approach.

jQuery - Disabling checkbox & adding attribute on click

I need checkboxes + table rows that share attributes to be enabled once the first checkbox has been ticked. (id for the table row + class for checkbox).
This is only half working
My problem is that if you have multiple boxes selected and uncheck just one, all of the checkboxes and table rows lose the disabled attribute.
https://jsfiddle.net/a1p7an7o/
HTML
<tr id="IN-HOUSE">
<input onchange="check();" class="IN-HOUSE" name="bill[]" type="checkbox">
<label for="Bill?">Bill?</label>
</td>
</tr>
Javascript
<script>
function check(){
$('input[name*=bill]').change(function() {
$t = $(this);
var $th = $(this).attr('class');
$c = $("tr[id!='"+$th+"']");
if ($(this).is(':checked')) {
$('input[name*=bill]').each(function() {
if ($(this).attr('class') != $th) {
$(this).not($t).prop('disabled', true);
$c.not($t).addClass( "disable" );
}
});
} else {
$('input[name*=bill]').each(function() {
if ($(this).attr('class') != $th) {
$(this).not($t).prop('disabled', false);
$("tr[id!='"+$th+"']").removeClass("disable");
}
});
}
});
}
</script>

jQuery stop script execution after if condition within click event

In this table, the rows are selectable only when Approved? column is empty. User can also add text in Deny Reason column.
When Deny button clicked, I want to make sure all deny reasons are filled in all selected rows before the rest of action can be executed. I tried to use return false , e.stopPropagation() , e.stopImmediatePropagation() and none of those works. As you can see in my example, alert("test") will always be executed. I want to stop that. Could you help?
$(function() {
var table = $("#myDataTable").DataTable({
info: false,
paging: false,
searching: false,
sorting: false
});
$("#myDataTable tbody").on('click', 'tr', function() {
var tr = $(this).closest("tr");
var rowText = tr.children("td").text();
var approveDeny = tr.children("td:nth-child(2)").text();
if (approveDeny == "") {
$(this).toggleClass('selected');
}
});
$("#myDataTable tbody tr td:nth-child(4)").click(function(e) {
if ($(this).prev().prev().text() == "") {
var text = $(this).text();
$(this).text('');
$('<textarea />').appendTo($(this)).val(text).select().blur(function() {
var newText = $(this).val();
var parentCell = $(this).parent();
parentCell.find('textarea').remove();
table.cell(parentCell).data(newText).draw();
});
}
e.stopPropagation();
});
$("#btnDeny").click(function(e) {
table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) {
var data = this.data();
if(data == "") {
alert( rowIdx + " is empty, you have to fill it.");
return false;
}
console.log(data);
});
alert("test");
});
});
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<table id="myDataTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Approved?</th>
<th>Date</th>
<th>Deny Reason</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td>Mickey Mouse</td>
<td>Yes</td>
<td>1/1/2016</td>
<td></td>
</tr>
<tr id="2">
<td>Minnie Mouse</td>
<td></td>
<td>1/3/2016</td>
<td></td>
</tr>
<tr id="3">
<td>Donald Duck</td>
<td></td>
<td>1/5/2016</td>
<td></td>
</tr>
</tbody>
</table>
<br/>
<div>
<input type="button" id="btnApprove" value="Approve">
<input type="button" id="btnDeny" value="Deny">
</div>
You can use a variable outside of the scope of your inner .every() function and change it within that function so you know if the data is valid or not.
$("#btnDeny").click(function(e) { // Outer scope function
var valid = true;
table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) { // inner scope function
var data = this.data();
if(data == "") {
valid = false;
alert( rowIdx + " is empty, you have to fill it.");
}
});
if (valid)
alert("Data valid");
});
Right, you need to assign the boolean output of every() to a variable, and then execute your alert only if that variable is true. Right now the result of the every() call is ignored, and the alert is executed regardless. Something like:
var isValid = table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) {
var data = this.data();
if(data == "") {
alert( rowIdx + " is empty, you have to fill it.");
return false;
}
console.log(data);
});
if (isValid) {
alert("test");
}

Categories