I am using the autodividersSelector function to display post date as divider text. I am stuck at the point of how to navigate to retrieve the date class. Below is the code and console log of the Div element in DOM.
If this question had been answered else where, please provide me with the link. Thanks
Code
$(document).on('pagebeforeshow', '#blogposts', function () {
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" ,
dataType: "json" ,
beforeSend: function () {$('.loader').show();},
complete: function () {$('.loader').hide();},
success: function (data){
$('#postlist').empty();
//setTimeout(function(){
$.each(data.posts, function (key, val) {
//Format date
var dateString = val.date.split(' ')[0];
var vdate = dateString.split("-")[1] + " " + monthStrings[parseInt(dateString.split("-")[1])] + ", " + dateString.split("-")[0];
//Output data collected into page content
var rtitle = $('<p/>', {'class' : 'vTitle', html: val.title}); rdate = $('<p/>', {'class': 'vDate' , html: vdate});
rid = $('');
var rappend = $('<li/>').append(rtitle, rdate);
$('#postlist').append($(rappend).wrapInner(rid).fadeIn(600));
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
//console.log(li);
var out = $(li).get(0)
console.log(out);
return out;
}
});
return (key !== 5);
});
$("#postlist").listview().listview('refresh').append('<div class="more-posts" style="text-align: center;">Load more posts...</div>');
// }, 2000);
},
error: function (data) {
alert("Service currently not available, please try again later...");
}
});
});
Result of output showing [objectHTMLLiElement] in the divider
HTML:
<!-- Page: Blog Posts -->
<div id="blogposts" data-role="page">
<div data-role="header" data-position="fixed">
<h2>My Blog Posts</h2>
</div><!-- header -->
<div data-role="listview">
<ul data-filter="true" data-filter-placeholder='Search blog posts...' data-theme="a" id="postlist"> </ul><!-- content -->
</div>
<div class="loader"><img src="css/images/loader.gif"/></div>
</div><!-- page -->
$('.vDate').each(
function(){
alert($(this).html());
}
);
OK this is the final code that worked for custom autodividersSelector:
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.find("p").map(function() {return $(this).text();});
var out1 = out.get(1);
return out1;
}
});
Related
I am submitting a html form through AJAX and then appending results at particular div element.The corresponding ajax is :-
$(document).ready(function(){
$('.commentbutton').click(function(){
var idb=$(this).attr('id');
var formid=$('#Comment'+idb);
datab=getFormData(formid);
$.ajax({
type:"POST",
url:'/submit/channelcomment',
data:datab,
success:function(data){
console.log(data.content);
console.log(data.profile);
var html="<div class='CommentRow'><a href='/Channel/"+data.profile+"/'style='font-weight: bolder;margin-right: 10px;display: inline-block;'>"+data.profile+"</a>"+data.content+"</div>"
console.log('Done');
idt=$('#CommentBody'+idb);
console.log(idt);
idt.append(html);
},
}),
event.preventDefault();
});
});
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
The desired position at which i'm trying to append html is as follows:-
<div class="CommentBody" id="CommentBody{{c.id}}">
</div>
Here c.id and idb equals to 1.But it is not appending html.
When you say
But it is not appending html.
What is actual behavior?
I tried the dummy code as below and it is working fine.
$(document).ready(function() {
$('.commentbutton').click(function() {
var html = "<div class='CommentRow'><a href='/Channel/data.profile/'style='font-weight: bolder;margin-right: 10px;display: inline-block;'>data.profile</a>data.content</div>"
var idb = '1';
idt = $('#CommentBody' + idb);
alert(idt);
idt.append(html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='commentbutton'>Comment</button>
<div class="CommentBody" id="CommentBody1">
</div>
I'm using the jquery and jquery UI plugin to drag and drop elements (folders and files) just like in a filebrowser.
I can manage to have the file go 'into' the folder, but not a folder to go into another.
Here is a demo :
There seems to be something conflicting, but I don't know where to look anymore.
The javascript is like this :
$(function () {
// fancytree is part of another script
$("#tree").fancytree({
expandLazy: true,
activate: function (event, data) {
var node = data.node;
if (node.data.href) {
window.open(node.data.href, node.data.target);
}
}
});
/* DRAG AND DROP STARTS HERE */
$(".listitems").draggable();
$(".droppable").droppable({
//preventCollision: true,
drop: function (event, ui) {
var draggableId = ui.draggable.attr("id");
var droppableId = $(this).attr("id");
//alert('FILE'+draggableId+' DROPED INTO '+droppableId);
$(this).append(ui.draggable);
var itemid = ui.draggable.attr('data-itemid');
var folderid = ui.draggable.attr('data-fldmid');
if (typeof folderid == 'undefined') {
folderid = 0;
}
if (typeof itemid == 'undefined') {
itemid = 0;
}
if (typeof droppableId == 'undefined') {
droppableId = 0;
}
$.ajax({
method: "POST",
url: "_ajax/filemanager/dragdrop.php",
//data : 'FileID='+ itemid +'&FolderID='+ droppableId,
data: 'FileID=' + itemid + '&FolderID=' + folderid + '&DropID=' + droppableId,
}).done(function (data) {
var result = $.parseJSON(data);
if (folderid == 0) {
//alert('FILE MOVED - FileID='+ itemid +'&FolderID='+ folderid+'&DropID='+ droppableId);
// Done moving file, hiding it
$("div#" + itemid).hide(500);
} else {
//alert('FOLDER MOVED - FileID='+ itemid +'&FolderID='+ folderid+'&DropID='+ droppableId);
// Done moving directory, hiding it
$("div#" + folderid).hide(500);
}
//$("div#"+folderid).hide(500);
//$("div#"+droppableId).hide(500);
});
}
});
$(".listitems").sortable();
$(".listitems").disableSelection();
var shouldCancel = false;
$('.dragMe').draggable({
containment: '.moveInHere',
revert: function () {
if (shouldCancel) {
shouldCancel = false;
return true;
} else {
return false;
}
}
});
$('.butNotHere').droppable({
over: function () {
shouldCancel = true;
},
out: function () {
shouldCancel = false;
}
});
});
And here is the html
<div class="box-body">
<div class="table-responsive mailbox-messages moveInHere" style="overflow: hidden; min-height:600px;">
<p>
<!--id, data-fldmid and data-itemid were added for testing purposes -->
<div class="boxFile small droppable listitems dragMe drag" id="D.4" data-fldmid='D.4' data-itemid='4'>
<a href="?n=9">
<div class="ffolder small yellow"></div>
</a>
<div class="boxFileTitle">Folder 1 (4)</div>
</div>
<div class="boxFile small droppable listitems dragMe drag" id="D.7" data-fldmid='D.7' data-itemid='7'>
<a href="?n=7">
<div class="ffolder small yellow"></div>
</a>
<div class="boxFileTitle">Folder A (7)</div>
</div>
<p>
<div style="" class="boxFile small listitems butNotHere dragMe drag" id="26" data-itemid='26'>
<img src='image.php?id=26' class='UploadedImageThumb'>
<div class="boxFileTitle">2016-12-12 14.50.14.jpg26</div>
<div class="boxFileOption">Preview | Edit | Trash</div>
</div>
</p>
<p>
<div style="" class="boxFile small listitems butNotHere dragMe drag" id="25" data-itemid='25'>
<img src='image.php?id=25' class='UploadedImageThumb'>
<div class="boxFileTitle">test.jpg25</div>
<div class="boxFileOption">Preview | Edit | Trash</div>
</div>
</p>
</p>
</div>
</div>
The 'butNotHere' class is to prevent files to be on top of each other. All this works fine, except the folder-into-folder dragging as described above.
I found the error, the variable in JS (folderid) had a letter 'D' in front of the real id. I did this during test to check if it was a file being moved or folder. So 'F' or 'D'.
So I changed this line
data-fldmid='D.7'
To this and it worked
data-fldmid='7'
I'm trying to write some simple Javascript that uses the Trello API to get all boards / lists / cards from my account and add them into an sortable table (using the Datatables jquery plugin).
I've so far managed to write a jsfiddle that gets all this information and writes it to a page, but I can't work out how to store all this information into some sort of data structure that can then be passed to the datatable plugin.
This is the fiddle I have so far that gets the data from Trello:
JS Fiddle Link
var carddata = [];
Trello.members.get("me", function(member) {
$("#fullName").text(member.fullName);
var boardUrl = "";
boardUrl = "members/me/boards";
Trello.get(boardUrl, function(boards) {
$.each(boards, function(ix, board) {
Trello.get("/boards/" + board.id + "/lists", function(lists) {
$.each(lists, function(ix, list) {
Trello.get("lists/" + list.id + "/cards", function(cards) {
$.each(cards, function(ix, card) {
console.log("boardname: " + board.name + "; list name: " + list.name + "; card name: " + card.name);
carddata.push(
"boardname: " + board.name +
"; list name: " + list.name +
"; card name: " + card.name
);
var $tablerow = "";
$tablerow = $(
"<tr><td>" + board.name +
"</td><td>" + list.name +
"</td><td>" + card.name +
"</td></tr>"
).appendTo("#table_body");
});
/*
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
*/
});
});
});
});
});
});
// **** carddata array is empty at this point ****
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
It loops through all boards, lists and cards and currently adds what it finds to a html table (and also an array). I then use the Datatables plugin to change that HTML table into a sortable table.
However the plugin is seeing the HTML table as empty (from what I can see), I presume this is because of something like the plugin code being called before the Javascript builds up the table in HTML.
So instead I planned to add all the data into an array, and then pass that array into the datatable as a datasource, but I can 't see how to make the array accessible outside the very inner loop. From doing some searches I think this is to do with closures and scope but I'm struggling to understand how they work (I'm very new to Javascript).
Is anyone able to help me get this basic code working and show me what I'm doing wrong?
Thanks,
David.
The following code snippet demonstrate how to add data to data table after table created. For how to wait for all asyn requests completed, setTimeout is used to simulate Trello.get method for the asyn behavior.
var boardHash = {};
var listHash = {};
var updateLoggedIn = function() {
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var loadCardData = function(){
var carddata = [];
var loadMember = function() {
setTimeout(function(){
console.log("Member loaded");
loadBoard();
},2000);
}
var loadBoard = function() {
setTimeout(function(){
console.log("Boards loaded");
var listPromises = [];
loadList(["boardA","boardB","boardC"],listPromises);
$.when.apply($, listPromises).then(function(){
table.rows.add(carddata).draw("");
});
},1000);
};
var loadList = function(boards,listPromises){
$.each(boards,function(boardIndex, boardValue){
var listDefered = $.Deferred();
listPromises.push(listDefered.promise());
setTimeout(function(){
console.log(boardValue+" lists loaded");
var cardPromises = [];
loadCard(["listA","listA","listC"],boardValue,cardPromises);
$.when.apply($, cardPromises).then(function(){
listDefered.resolve();
});
},(boardIndex+1)*900);
});
};
var loadCard = function(lists,boardValue,cardPromises){
$.each(["listA","listA","listC"],function(listIndex, listValue){
var cardDefered = $.Deferred();
cardPromises.push(cardDefered.promise());
setTimeout(function(){
console.log(boardValue+" "+listValue+" cards loaded");
$.each(["cardA","cardB","cardC"],function(cardIndex, cardValue){
carddata.push({
"boardName":boardValue,
"listName":listValue,
"cardName":cardValue
});
});
cardDefered.resolve();
},(listIndex+1)*800);
});
};
loadMember();
};
var logout = function() {
updateLoggedIn();
};
$("#connectLink")
.click(function() {
loadCardData();
});
$("#disconnect").click(logout);
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var table = null;
$(document).ready( function () {
table = $('#table_id').DataTable({
columns: [
{ data: 'boardName' },
{ data: 'listName' },
{ data: 'cardName' }
]
});
} );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="loggedout">
<a id="connectLink" href="#">Connect To Trello</a>
</div>
</head>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
<a id="disconnect" href="#">Log Out</a>
</div>
<div id="output"></div>
</div>
<table id="table_id" class="display" border=1>
<thead>
<tr>
<th>Board</th>
<th>List</th>
<th>Card</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="console-log"></div>
</html>
For adding data to data table
So in your code, add the columns options to the data table, and use rows.add method to add data to data table when all ajax request are done.
Wait for all ajax request completed
The most tricky part is how to ensure all response are done, this can be achieved by $.Deferred() and $.when.apply, see JQuery document and What does $.when.apply($, someArray) do? for more details.
I am trying to make a ajax click to load div function. But the click function doesn't work. What i am doing wrong here? Anyone can help me in this regard ?
DEMO from Jsfiddle
var response = '<div class="icon_b">
<div class="clickficon"></div>
<div class="emicon-menu MaterialTabs">
<ul>
<li class="tab active"> Starks</li>
<li class="tab"> Lannisters</li>
<li class="tab"> Targaryens<span></span></li>
</ul>
<div class="panels">
<div id="starks-panel1" class="panel pactive"> a </div>
<div id="lannisters-panel1" class="panel"> b </div>
<div id="targaryens-panel1" class="panel"> c </div>
</div>
</div>
</div>';
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
success: function (returnHtml) {
e.find('.user-container').html(returnHtml).promise().done(function () {
$('.emoticon').addClass('loaded');
});
}
});
}
function hideProfileTooltip() {
$('.the-container').removeClass('loaded');
}
$('body').on('change', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
}, function () {
hideProfileTooltip();
});
});
callback function is not valid in there,
//on load,click is more prefer than change
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
//don't call like this
//, function () {
// hideProfileTooltip();
// });
I have the following html structure:
<div id="gw-sidebar" class="gw-sidebar">
<div class="nano-content">
<ul class="gw-nav gw-nav-list">
<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>
//===>Need to add the new list using Jquery here
</ul>
</div>
</div>
I want to add a list as shown below using jquery to the class 'init-un-active' shown above:
<li class="init-arrow-down"> <span class="gw-menu-text">Scenario-1</span> <b class="gw-arrow"></b>
<ul class="gw-submenu">
<li> Scenario </li>
<li> Resolutions </li>
<li> Triggers </li>
</ul>
</li>
How do i use jquery to add this code dynamically to the aforementioned class?
I have tried the following but it wont work:
<script type="text/javascript">
function loadScenarioForm () {
SideMenu.createBaseEntry();
// ScenarioForm.create();
}
var SideMenu = {
container : null,
scenarioCount : 0,
scenarioTxt : "Scenario",
ResolutionsTxt : "Resolutions",
TriggersTxt : "Triggers",
menuLink : "javascript:void(0)",
subMenuLink1 : "javascript:void(0)",
subMenuLink2 : "javascript:void(0)",
subMenuLink3 :"javascript:void(0)",
createBaseEntry : function createDefault () {
this.container = $(document.createElement('div'));
this.container.addClass('gw-sidebar');
var html = "";
html += '<div id="gw-sidebar" class="gw-sidebar">';
html += '<div class="nano-content">';
html += '<ul class="gw-nav gw-nav-list">';
html += '<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>';
html += '</ul></div></div></div>';
this.container.append(html);
$('body').append(this.container);
this.scenarioCount++;
this.container.append(this.createEntry(scenarioCount));
},
createEntry : function createDefault (index) {
var list = $('ul.mylist');
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(list);
return list;
},
</script>
Please advise,
Thanks!
You can make your <li> as a template and append it to the <ul> using jquery. You can try something like this Fiddle:
$(document).ready(function(){
$('a').click(function() {
var template = $('#hidden-template').html();
$('.gw-nav').append(template);
});
});
if ($(".init-un-active").length == 0) {
$.ajax({
url: 'URL From where you want to load ...',
type: 'POST',
data: { id: ID}, // pass your data here if any .. else keep empty
success: function (data) {
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
$(".init-un-active").html(data);
},
error: function () {
alert('Unable to load menu...');
}
});
}
else {
if ($(".init-un-active ul").length > 0) {
$(".init-un-active ul").css("display", "none");
$(".init-un-active").css("display", "block");
}
}
Explanation:
if ($(".init-un-active").length == 0)
This condition is used to check if there are already item loaded in li .. if yes then no need to call ajax.. just hide show that menu..
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
this css is applied to show menu infront and hide all content beside this menu..
this.container.append(html);
$('body').append(this.container);
instead of this try this
$(".init-un-active").html(html);