I am using this CSS file http://daneden.github.io/animate.css/ to add some animation to the web site I am building.
The thing is I need to play an animation when I delete an item from a list for example, but how can I do that since the element is no longer in the DOM?
All right,
here is my jsp code:
<tbody class="filter">
<c:forEach var="message" items="${messages}">
<tr id="${message.id}" class="body">
<td>${message.name}</td>
<c:choose>
<c:when test="${not empty message.file}"><td>${message.file.name}</td></c:when>
<c:otherwise><td>${message.tts}</td></c:otherwise>
</c:choose>
<td class="icon"><i id="delete" class="icon-trash icon-hover"></i></td>
</tr>
</c:forEach>
</tbody>
And some jQuery:
$.ajax({
type: "GET",
url: "message/delete/" + id,
dataType: "json",
success: function(response) {
if (response.status == "OK") {
$row.addClass('animated flipOutX');
// Here I need to run an animation before I delete the item.
$('#messageTable tr#' + id).remove();
}
}
});
Thank you again for your help!
UPDATE:
Demo http://jsfiddle.net/g3WLM/1/
Related
I really am struggling with something that I thought was simple...
I am making a simple search-result table based on $.getJSON call, and want to keep my code as "generic" as possible.
In my (simplified) HTML :
<form id="searchForm">
(...)
<button type="button" onclick="search()">Search</button>
</form>
(...)
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
(...)
<td data-bind="text: BAR"></td>
</tr>
</tbody>
Then in my javascript (in script tags lower in the page):
var search = function(){
var form = $('#searchForm');
$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
console.log(jsonAnswer);
if(typeof viewModel === 'undefined'){
var viewModel = ko.mapping.fromJS(jsonAnswer);
ko.applyBindings(viewModel);
}
else{
ko.mapping.fromJS(jsonAnswer, viewModel);
}
$('#divResults').show();
// console.log(viewModel)
});
}
This works fine on the first "search" click... but not the following : Error You cannot apply bindings multiple times to the same element.
As you can guess, this very ugly "if" testing viewModel is a desperate attempt to get rid of that error.
I've tried many things but I just can't figure out how to do it properly...
I've read this Knockout JS update view from json model and this KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element but it didn't help me much... maybe because the search() function isn't called on load (and indeed shouldn't be).
Any KO master to give me a clue? Thanks in advance for your help!
This is how I would be approaching what you are trying to accomplish.
var searchService = {
search: function(form, vmData) {
//$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
var jsonAnswer = [{
FOO: "Item 1 Foo",
BAR: "Item 1 Bar"
}, {
FOO: "Item 2 Foo",
BAR: "Item 2 Bar"
}]
ko.mapping.fromJS(jsonAnswer, [], vmData);
//})
}
};
var PageViewModel = function() {
var self = this;
self.data = ko.observableArray();
self.hasResults = ko.pureComputed(function() {
return self.data().length > 0;
});
self.search = function() {
var form = $('#searchForm');
searchService.search(form, self.data);
};
};
ko.applyBindings(new PageViewModel());
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<form id="searchForm">
<button type="button" data-bind="click:search">Search</button>
</form>
<div data-bind="visible: !hasResults()"><b>No Results</b></div>
<div data-bind="visible: hasResults">
<table class="table">
<thead>
<tr>
<td>FOO</td>
<td>BAR</td>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
<td data-bind="text: BAR"></td>
</tr>
</tbody>
</table>
</div>
<br/>
<pre><code data-bind="text: ko.toJSON($root)"></code></pre>
I am working on asp.net mvc project.
I want to get the cell value from the selected row (row in which "Manage "button is clicked).
in this case value of userID.
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th width="45%">User ID</th>
<th width="45%">User Name</th>
<th width="5%">View</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TypeList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
<input id="Manage2" class="btn btn-primary" type="button" value="Manage" />
</td>
</tr>
}
</tbody>
I am calling jQuery click function and Ajax call and want to send the UserId value in data from selected row to the controller.
below is the jQuery ajax call,
<script type="text/javascript">
$(document).ready(function () {
$('#Manage2').click(function () {
//alert(1);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: '1' },
cache: false,
type: "POST",
success: function (data) {
$("#Data").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
</script>
Below is the view screen shot,
You can actually store the UserId value with html 5 data attribute on the button itself.
Your current code has Id attribute value hard coded inside a loop, which will create more than one element with same Id value. That is invalid HTML!
Remove the Id and use a more generic selector to wire up the click event. Here I added another CSS class "manage" to the button.
<input data-userid="#item.UserId" class="btn btn-primary manage"
type="button" value="Manage" />
and now
$(document).ready(function () {
$('.manage').click(function () {
var id = $(this).data("userid");
alert(id);
// use id for your ajax call
});
});
You do not necessarily need to add the extra css class only to use that as the selector later. Since you are adding a data attribute, you may simply use that as well for your jQuery selector.
$(function () {
$('[data-userid]').click(function () {
var id = $(this).data("userid");
alert(id);
// use id
});
});
You have invalid html because of the duplicate id attributes in your button.
Remove the id="Manage2" and replace with a class name and data- attribute for the value
<input data-id="#item.UserId" class="btn btn-primary Manage2" type="button" value="Manage" />
Then in the script, get the value using
$('.Manage2').click(function () { // class selector
var id = $(this).data('id);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: id },
....
Alternatively you could use relative selectors
$('.Manage2').click(function () {
var id = $(this).closest('tr').children('td:first').text();
....
I want create Jquery Datatable with Paging,Sorting,Searching in my ASP.NET web Api project as this youtube clip
in my bootstrap table as shown below. I don not recieve any Error but not showing me pagin field, serach field .. nothing showing me just my table. I understan it's not the same table form as that youtube clip but how should I do have the same functionality as him.
<!DOCTYPE html>
<html>
<head>
<title>Countries</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.1.1.js"></script> // Tried even with jquery-1.12.4.js
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<table class="table table-bordered table-hover table table-responsive success" id="countriesTable">
<thead>
<tr>
<th>
Country Id
</th>
<th>
Country name
</th>
<th class="col-md-2">
Action
</th>
</tr>
</thead>
<tbody class="tbody"></tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
$('#countriesTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
});
loadCountries();
}
function loadCountries() {
$('#compTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
});
$.ajax({
url: "/Api/Countries",
type: "GET",
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem('accessToken')
},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.CountryId + '</td>';
html += '<td>' + item.CountryName + '</td>';
html += '<td><Button class="btn btn-primary" onclick="return getByID(' + item.CountryId + ')">Edit</button> <Button class="btn btn-danger btn-md" onclick="return Delete(' + item.CountryId + ')">Delete</Button></td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (jqXHR) {
if (jqXHR.status == "401") {
$('#errorModal').modal('show');
}
else {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
}
});
}
</script>
You have to initialize the table correctly and also add proper dependent library from the documentation page. To get you started
$('#countriesTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
})
For the small arrow buttons in the column heads (which indicates sorting direction etc.) you need to add proper glyphicon libraries.
You can learn more options here.
How to find the proper dependent library?
Check this example. In the example section there 3 parts HTML, CSS and javascript. They mentioned the libraries there. You need to add them in the correct order they are mentioned.
As per your requirement you need to feature that dattable provides with table generation. After ajax call is made a response is found. Now you get the data from it and map it to appropriate columns.
$('#my-table').DataTable({
ajax: {
url:websiteurl,
data:function(dtl){
}
},
columns: [
{ data: 'col1'},
{ data: 'col2'},
]
});
HTML:
<table id ="my-table" class="table table-striped table-responsive sorting " >
<thead>
<tr>
<td>col1</td>
<td>col2</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Remember
For this you hvae to build the json output in the fom of array of objects.
JSONArray ja= new JSONArray();
JSONObject jo = new JSONObject();
jo.put("col1",col1val);
jo.put("col2",col2val);
ja.put(jo);
return ja in the response.
You might think
Can I put a html button code in a json string ..yes you can. Try that.
Referrence:Link
Can i implement a refresh button in twig template that will reload my entity data on click ?
Here is my controller :
public function indexAction() {
$repositoryForHistory = $this->getDoctrine()->getManager()->getRepository("PagesBundle:histories");
$histories = $repositoryForHistory->findBy(Array(), Array('date' => 'DESC'));
return $this->render('PagesBundle:Default:index.html.twig', array(
'histories' => $histories));
}
}
And the div i want to reload :
<tbody>
{% for history in histories %}
<tr>
<td class="center" style="color: #ADADAD;">
<i class="fa fa-calendar-o"></i>
</td>
<td>
<span class="bold-text text-small">{{history.user}} {{history.action}} {{history.featureName}}</span>
</td>
<td class="center" style="color: #ADADAD;">{{history.date|date('d-m-Y H:i')}}</td>
</tr>
{% endfor %} </tbody>
<a class="panel-refresh" href="#"> <i class="fa fa-refresh"></i> <span>Refresh</span></a>
You can make an ajax request and send it by clicking on Refresh button, and on success just replace html of the element you want to update (actually there is no div in your template and I don't understand exactly what do you mean by div).
So, for this you have to create a special controller action which will return a poor html without layout.
It's the simplest way.
Also you can take a look at angularjs. But in some sense it might be a bit more complicated.
You need to do something with AJAX, so that when somebody clicks the 'refresh button' it makes an XMLHttpRequest to Symfony, which returns a response that contains only the <tr>s (not the wrapping table, or the <head>, etc).
In jQuery (you didn't say you were using it, but the JavaScript is more complicated to write):
$('.panel-refresh').click( function(event, ui) {
// prevents the browser following the click
event.preventDefault();
// replaces the contents of `<tbody>` with the response from the controller
$('tbody').load('/path/to/action');
}
and replace '/path/to/action' with the actual path to the action.
thank you guys #Alex and #Blowski here is the solution :
in my Controller
function reloadHistoryAction() {
$repositoryForHistory = $this->getDoctrine()->getManager()->getRepository("PagesBundle:histories");
$histories = $repositoryForHistory->findBy(Array(), Array('date' => 'DESC'));
$html="";
foreach ($histories as $history) {
$html .="<tr>
<td class='center' style='color: #ADADAD;'>
<i class='fa fa-tasks'></i>
</td>
<td>
<span class='bold-text text-small'>".$history->getUser()." ".$history->getAction()." ".
$history->getFeatureName()."
</span>
</td>
<td class='center' style='color: #ADADAD;'>
". $history->getDate()->format('d-m-Y H:i')."
</td>
</tr> ";
}
return new Response($html);
}
And in my twig template an ajax call to the controller action :
$('.panel-refresh').click(function (e) {
e.preventDefault();
$.ajax({
url:'{{path('history/reload')}}',
type: "POST",
cache: "false",
dataType: "html",
success: function (data) {
$("tbody").html(data);
}
});
});
Thank you very much!
Is there a way to modify css attribute directly using jstl?
Below is what I want to do
<div id="error" align="center">
<img src='resources/warning.png'/>
<c:if test="${not empty error}">
<c:out value='${error}' /> //if i enter here, I want #error 'display' to be 'block'
</c:if>
</div>
So you might say, why not just have the css set to display:block, and put the if tags like this
<c:if test="${not empty error}">
<div id="error" align="center">
<img src='resources/warning.png'/>
<c:out value='${error}' />
</div>
</c:if>
That would be fine, if the only source of my errors were from the controller and passed back in the model. However, I am also making AJAX calls, and say there is a problem browser side, I need to display the error still.
So to do this, for example in my ajax call I do
$.ajax({
url: "url",
beforeSend: function(){
$("body").css("cursor", "wait");
},
dataType:"json",
timeout:15000,
cache: false,
async: false,
success: function(data){
document.getElementById("error").innerHTML="";
document.getElementById("error").style.display = "none";
$("body").css("cursor", "default");
},
error: function(jqXHR, textStatus, errorThrown){
if (textStatus =="timeout"){
document.getElementById("error").innerHTML="Request timed out!";
}
else{
document.getElementById("error").innerHTML= jqXHR.responseText;
}
document.getElementById("error").style.display = "block";
// $("#loading").fadeOut('medium');
$("body").css("cursor", "default");
}
});
<div id="error" align="center" <c:if test="${empty error}">style="display: none;"</c:if>>
<img src='resources/warning.png'/>
<c:if test="${not empty error}">
<c:out value='${error}' />
</c:if>
</div>
or
<div id="error" align="center" style="display: ${(empty error) ? 'none': 'block'};">
<img src='resources/warning.png'/>
<c:if test="${not empty error}">
<c:out value='${error}' />
</c:if>
</div>
should do what you want.
Here's how I did it
<div id="error" align="center">
<img src='resources/critical.png'/>
<span id="errorText">
<c:out value='${error}' />
</span>
</div>
So now the display property is only appying to the containing div 'error'
My jsp is setting text in the 'errorText' field
My ajax javascript is also doing this if it finds an error.
Then, in my javascript, it checks if 'errorText' has anything in it, and sets its display appropriately
$.ajax({
//url: "./test.go?station="+stName+"&date="+rDate,
url: "./getAssignments.go?station="+stName+"&date="+rDate,
beforeSend: function(){
// $("#loading").fadeIn('medium');
$("body").css("cursor", "wait");
},
dataType:"json",
timeout:15000,
cache: false,
async: false,
success: function(data){
document.getElementById("errorText").innerHTML="";
document.getElementById("error").style.display = "none";
pucksJSON=data;
reconstructGates( pucksJSON );
setStationName(stationName);
refresh_time = new Date(); //reset the time counter
// $("#loading").fadeOut('medium');
$("body").css("cursor", "default");
},
error: function(jqXHR, textStatus, errorThrown){
refresh_time = new Date(); //reset the time counter
if (textStatus =="timeout"){
document.getElementById("errorText").innerHTML="Request timed out!";
}
else{
document.getElementById("errorText").innerHTML= jqXHR.responseText;
setStationName(stationName);
reconstructGates( null );
}
document.getElementById("error").style.display = "block";
// $("#loading").fadeOut('medium');
$("body").css("cursor", "default");
}
});
This only works because I set up my controller to return a bad response code if it sets an error. So the Ajax fails and goes to the error section.