Copy a row between 2 jquery Datatables and then update my DB - jquery-ui

I already have a portion of this working using Jquery-Ui, I'd appreciate some further input.
I am able to drag and drop a row from Table1 onto Table2.
issues
When I drop the new row, it does appear on table2 but table2 collapses for some reason and I have to expand it to see the new row
Table1 looks like the row was removed but if you use the Order arrow it reappears. - This issue has been fixed
Additional Question...
I wish to push this new row of data into my db via ajax call...should I try to send the data at the end of the table2.droppable function or should I use some datatbles function in table2 to realise there is new data and then fire?
<table class="dataTable" id="table1">
<thead>
<tr>
<th>Rendering engine</th>
</tr>
</thead>
<tbody>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
</tbody>
</table>
<h2>Table 2</h2>
<table class="dataTable" id="table2">
<thead>
<tr>
<th>Rendering engine</th>
</tr>
</thead>
</table>
var t1 = $('#table1').DataTable();
var t2 = $('#table2').DataTable();
//this will hold reference to the tr we have dragged and its helper
var c = {};
$("#table1 tr").draggable({
helper: "clone",
start: function (event, ui) {
c.tr = this;
c.helper = ui.helper;
}
});
$("#table2").droppable({
drop: function (event, ui) {
t2.row.add(c.tr).draw();
// <-- Do this if you want to remove the rows from the first table
$(c.tr).remove();
$(c.helper).remove();
//Redraw Table1
t1.draw();
// -->
return false;
}
});
Fiddle

I would use the code as follows. This will allow you to handle any exceptions that may occur in the process of inserting data in the database.
var t1 = $('#table1').DataTable();
var t2 = $('#table2').DataTable();
//this will hold reference to the tr we have dragged and its helper
var c = {};
$("#table1 tr").draggable({
helper: "clone",
start: function (event, ui) {
c.tr = this;
c.helper = ui.helper;
}
});
$("#table2").droppable({
drop: function (event, ui) {
//Insert the data into my database.
insertData(function (success) {
if (success) {
//Move the row.
t2.row.add(c.tr).draw();
$(c.tr).remove();
$(c.helper).remove();
//Re-draw the tables.
t1.draw();
t2.draw();
}
else {
//Handle a failed insert.
alert("Unable to insert data!");
}
});
}
});
function insertData(cb) {
//Perform some AJAX.
//Test a success.
cb(true);
//Test a Failure.
//cb(false);
}

Related

how to disabled asp-action link after one click

i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
<a asp-action="AcheterLivre" asp-Controller="Achat" asp-route-id="#item.Isbn" id="disabled" onclick="return myFunction(this);"> Ajouter
i try something with jquery but its dont work well
i tried this
<script>
function myFunction() {
$("#disabled").one("click", function () {
alert("this book is already in the cart");
});
}
i have this function in my class
its verify if the books is in the cart maybe i should use it ?
public bool IsPresent(string isbn)
{
//rechercher si l'isbn correspond a un livre de la liste
AchatLivreViewModel livre = ListeElements.Find(element => element.Isbn == isbn);
if (livre != null)
{
return true;
}
else
{
return false;
}
}
Why not trying this simple approach:
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Isbn
</td>
<td>
#item.Titre
</td>
<td>
<label class="btn btn-primary" style="padding:0">Add to Cart</label>
</td>
<td>
<label class="btn btn-danger" style="padding:0">Remove From Cart</label>
</td>
</tr>
}
</tbody>
And in your javascript, if you don't want to use Ajax, you can manage your cart items all on client side using an array of objects, Let's name it CartItems:
var CartItems = [];
$('.ADD2CART').click(function () {
if ($(this).closest('tr').hasClass("ExistingInCart")) {
alert('Already in Cart !!');
}
else {
// add this item to the Cart through Ajax or
// local javascript object: e.g.:
CartItems.push({
ISBN: $(this).closest('tr').find('td:eq(0)').text().trim(),
Title: $(this).closest('tr').find('td:eq(1)').text().trim(),
});
$(this).closest('tr').addClass("ExistingInCart");
}
return false; //to prevent <a> from navigating to another address
});
$('.RemoveFromCART').click(function () {
$(this).closest('tr').removeClass("ExistingInCart");
var isbn = $(this).closest('tr').find('td:eq(0)').text().trim();
CartItems = CartItems.filter(x => x.ISBN !== isbn);
return false;
});
Once you need to submit or post the page, you have all the already selected books in CartItems array.
To add this javascript code to your view, choose one of the options:
Put this block at the bottom of your view and copy the above script inside the <script></script> tag:
#section scripts{
<script>
.... copy it here ...
</script>
}
copy the script code inside a newFile.js and add it to your view
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/newFile.js"></script>
You may decide to bundle this newFile.js
try this:
Ajouter
And your Javascript:
function foo(input) {
if ($(input).attr('yetClickable') === '1') {
$(input).attr('yetClickable', '0');
return true;
}
else {
// this false returning will counteract the effect of click event on the anchor tag
return false;
}
}
Once an Item is removed from the cart, again you need javascript to select that Item by its Id and change the yetClickable attribute back to 1 (in order to be clickable).
Note: This idea above (upon your scenario) works until the page is not reloaded. Otherwise, you need to handle ADD/Remove operations on the Cart through Ajax.
Hope this helps.

ng-table get data from rails api not working

I'm trying to make a simple table with pagination by using Angularjs ng-table.
I included the js and css files to my rails 3 layout. When page first loaded, it displays a table then fires a http get to rails controller to get json(it works fine until this point).
What I'm trying to do is add pagination to my table.
I received error "angular is not defined" and there is no request from http get to rails controller. Please show me what I'm doing wrong here.
Thank you
(function(){
var app = angular.module("apTags", ["ngTable"])
// call back after table finished ng-repeat
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
tableResponsiveAdjustHeight();
});
}
}
}
});
app.controller("apTagsController", [ "$http", function($scope, ngTableParams, $http){
// table has empty data when page first loaded
var apTags = this;
apTags.tags = [];
// Then it fires a http get to rails api to get data and append to table
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
$http.get("ap_tags.json", {params: { api: true, page: params.page() } }).success(function(data){
apTags.tags = data;
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
});
}
});
}]);
})();
<div class="container" ng-app="apTags">
<div ng-controller="apTagsController as list">
<p><strong>Page:</strong> {{tableParams.page()}}</p>
<p><strong>Count per page:</strong> {{tableParams.count()}}</p>
<table ng-table="tableParams" id="table_tags" class="table table-condensed table-bordered table-hover">
<tr ng-repeat="tag in list.tags" on-finish-render="ngRepeatFinished">
<td data-title="'Tag'">{{tag.name}}</td>
<td data-title="'Share'">{{tag.share}}%</td>
<td data-title="'Direct Product Count'"></td>
</tr>
</table>
</div>
</div>

How to select the all the rows in jquery data table

I have two buttons in my page "Select All" and "Deselect All". I need to select the all the rows when i click the select all button and save the list of id in my variable. When Click deselect ll button it should be deselect the all rows . How will we do that?
[HttpPost]
public ActionResult Action Name(pssing value)
{
DataTable dataTable = new DataTable();
// my code
var MyModel = new List<List<string>>();
foreach (var joblist in Jobs)
{
var sublist = new List<string>();
sublist.Add(checked.false);
sublist.Add(values));
sublist.Add(values));
....etc
baseModel.Add(sublist);
}
return new DataTableResult(return);
}
Html :
<table cellpadding="0" cellspacing="0" border="0" class="display" id="AssignJobsTable" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>ID</th>
etc ......
</tr>
</thead>
script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
When i click the select all check box it cant bind the value form the controller.
try this
$('table#tableId> tbody > tr').addClass('highlight');
$('table#tableId> tbody > tr').removeClass('highlight')addClass('noHeilight');
sample table
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
</table>
sample script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
you should set id attr for checkboxes and put row id in the id attr and use the below code for selecting and deselecting:
$(document).ready(function(){
$("#selectall").click(function () {
var isSelect;
if($(this).is(":checked")) {
isSelect=true;
}else{
isSelect=false;
}
$("table tr td input[type=checkbox]").each(function(){
if(isSelect) {
$(this).prop('checked', true);
SelectedItems+=$(this).val()+":";
}else{
$(this).prop('checked', false);
SelectedItems="";
}
$("#Result").html(SelectedItems);
});
});
});
This is my approach of keeping track of all the selected rows in a datatable.
http://www.datatables.net/release-datatables/examples/plug-ins/plugin_api.html
The idea is to check the current page that the user is on and select/deselect the rows that is currently being viewed. You would loop through the page's rows and store the selected row into an array for future reference.
With this approach you would limit the time it takes to select/deselect all rows in the table.
Only show whats needed base on the view that user is seeing.
No hang up because the table is too busy checking/unchecking each row.
//stored checked box list
var result = [];
var selectAll = false;
var table5 = $('#example5').dataTable({
'fnDrawCallback':function(oSettings){
var anNodes = this.oApi._fnGetTrNodes( oSettings );
var anDisplay = $('tbody tr', oSettings.nTable);
//write your logic for pagination
//example
/*
$('tbody tr td:first-child input[type=checkbox]').on('click', function(){
if($(this).is(':checked')){
if($.inArray(....) != -1){push result}
}else{
if($.inArray(....) != -1){splice result}
}
}
if(selectAll){
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//add to the array
}
}else{
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//delete from the array
}
}
*/
}
})
That would be your logic for keeping track of the checked row.

get the row data using jquery by clicking buttons for that row

I am having issues to get the table data in the row if a button is selected. I have two buttons approve and deny and based on what button user clicks I want to grab the data using query. can get the row numbers and stuff just not the row data. I need to get the id and tester.
here is what I have
<table id="mytable" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Tester</th>
<th>Date</th>
<th>Approve</th>
<th>Deny</th>
</tr>
</thead>
<tbody>
<tr class="test">
<td class="ids">11565 </td>
<td class="tester">james</td>
<td>2012-07-02 </td>
<td><Button id="Approved" type="submit" >Approved</button>
</td>
<td><Button id="deny_0" type="submit" >Denied</button>
</td>
</tr>
</tbody>
</table>
here is my javascript to get the tr and td number but I am not sure how to use it to get what I need
$(document).ready(function() {
/*$('#cardsData .giftcardaccount_id').each(function(){
alert($(this).html());
}); */
$('td').click(function(){
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
// alert($tds.eq(0).text());
console.log($("tr:eq(1)"));
// $("td:eq(0)", this).text(),
});
});
$(document).ready(function(){
$('#Approved').click(function(){
var id = $(this).parent().siblings('.ids').text();
var tester = $(this).parent().siblings('.tester').text();
console.log(id);
console.log(tester);
});
});​
JSFiddle
$(function(){
$('button').on('click', function(){
var tr = $(this).closest('tr');
var id = tr.find('.ids').text();
var tester = tr.find('.tester').text();
alert('id: '+id+', tester: ' + tester);
});
});​
FIDDLE
I would use closest() to get the tr and then descend from there.
var tr = $('td').closest('tr')
Also I think this is unnecessary, in your example that would be $(this):
$(this).parent().children().index($(this)) // === $(this)
$('table').on('click', 'button', function() {
var parentRow = $(this).parent().parent();
var id = $('td.ids', parentRow).text();
var tester = $('td.tester', parentRow).text();
alert('id: ' + id + ', tester: ' + tester);
});​

KnockoutJS: ko.mapping.fromJS problems

My JS:
<script type="text/javascript">
function DictionaryEntry() {
var self = this;
self.Simplified = ko.observable("");
self.Traditional = ko.observable("");
self.Phonetic = ko.observable("");
self.Definition = ko.observable("");
}
function DictionaryModel() {
var self = this;
self.entries = ko.observableArray([]);
}
var viewModel = new DictionaryModel();
viewModel.update = function () {
var self = this;
var f = $("#fSearch");
$.ajax({
url: f.attr('action'),
type: f.attr('method'),
data: f.serialize(),
success: function (result) {
self.entries = ko.mapping.fromJS(result, viewModel);
}
});
return false;
}
ko.applyBindings(viewModel);
</script>
Table html:
<table class="table table-striped">
<thead>
<tr>
<th>#T("Simplified")</th>
<th>#T("Traditional")</th>
<th>#T("Phonetic")</th>
<th>#T("Definition")</th>
</tr>
</thead>
<tbody data-bind="foreach: entries">
<tr>
<td data-bind="text: Simplified"></td>
<td data-bind="text: Traditional"></td>
<td data-bind="text: Phonetic"></td>
<td data-bind="text: Definition"></td>
</tr>
</tbody>
</table>
A button which triggers the update.. searches the dictionary and returns results to replace what is currently in the table:
<input type="submit" value="Search" class="btn" data-bind="click: update" />
in my action method, this is what is returned:
return Json(new
{
// here list is a List<T> with the 4 properties to display in UI
entries = list,
IndexOfPage = indexOfPage,
SizeOfPage = sizeOfPage,
TotalRecords = totalRecords,
Pages = (int)Math.Ceiling((double)totalRecords / sizeOfPage)
});
Problem I am having is that it seems to be stuck in an infinite loop for some reason. I put a breakpoint in the action and I can see it goes there over-and-over again... continuously..
What am I doing wrong? Completely new to knockout (and not exactly super at JS either, so please don't give a vague answer)
There is a callback that is called update in knockout.
What's happening is when you call the mapping, it's triggering that callback ( which exists as a function on the viewModel ). This is causing your update function to be called, thus causing an infinite loop.
http://knockoutjs.com/documentation/plugins-mapping.html
look for the section about Customizing object updating using “update”
If result has an entries propery that is your list, you should just have to 'ko.mapping.fromJS(result, viewModel)'. Setting entries to the result gives you an entries property with it's own entries property.

Resources