Append more Data into existing Data - javascript

I was hoping not to ask this question yet since I decided to read more and do more research but at the moment I am not getting much far with it.
This is my code:
function listPosts(data) {
var $count = data.count;
var limitposts = 5;
var $output = $('<ul class="posts" data-role="listview" data-filter="true">')
$.each(data.posts,function(i, val) {
console.log(i);
if (i<limitposts && i>=0) {
var $post = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('');
$output.append($post).appendTo('#postlist');
i++;
// return (i !== 4);
}});
}
HTML
<!-- Page: home -->
<div id="home" data-role="page" data-theme="d" data-title="My first App">
<div data-role="listview">
Display Messages
</div><!-- links -->
</div><!-- page -->
<div id="devotion" data-role="page" data-title="My first App">
<div data-role="header" data-theme="a" data-position="fixed"> <h2>Devotional Messages</h2></div><!-- header -->
<div data-theme="d" data-role="listview" id="postlist"> </div><!-- content -->
<div class="addMorePosts">Load More Posts...</div>
</div><!-- page -->
<script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript"></script>
I initially limited the number of Posts displayed by using the Return statement. I now changed it to For statement to see if I can increment the number of Posts displayed by the click of a button.
At this stage I am trying to figure out the best logic to use. I have tried to add another Function to achieve this but no luck. Still reading and researching but was hoping for guidance or good example

function addMorePosts ( data, offset, amount ) {
var $postsList = $('#postlist'),
posts = data.slice(offset, amount);
$.each(posts, function ( index, post ) {
$postsList.append(
'<li>' +
'<h3>' + post.title + '</h3>' +
'<p>' +
post.excerpt +
'' +
'</p>' +
'</li>'
);
});
}
JSFiddle: http://jsfiddle.net/V4Ucv/2/

Related

Multiple Bootstrap tabs remaining active when generated with jQuery

I have the following divs with special attributes that I am selecting with jQuery
<div data-tab-name="Description">
<!-- content -->
</div>
<div data-tab-name="Video">
<!-- content -->
</div>
<div data-tab-name="Reviews">
<!-- content -->
</div>
I am then taking those divs and turning them into individual Bootstrap tabs (& nav-tabs) and attempting to set the first tab-pane & nav-tab to active. This is the result:
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#description">Description</a>
</li>
<li>
<a data-toggle="tab" href="#video">Video</a>
</li>
<li>
<a data-toggle="tab" href="#reviews">Reviews</a>
</li>
</ul>
<div class="row tab-content">
<div class="tab-pane fade in active" id="description">
<!-- Content -->
</div>
<div class="tab-pane fade" id="video">
<!-- Content -->
</div>
<div class="tab-pane fade" id="reviews">
<!-- Content -->
</div>
</div>
Whenever I run the code it structures it as I intended, which is what w3school's boostrap tab example shows (Dynamic Tabs), but multiple tabs are staying active when I switch between them which prevents them from being clicked twice.
What would I need to do to make it behave as it normally does when entering the html for the tabs directly? https://codepen.io/BBell/pen/RBLmEr
I'm not sure why stacksnippet is showing a script error, but it continues to show even if I remove the JS (http://recordit.co/8mazS35U9r). Here is a backup codepen that worked better for me:
https://codepen.io/BBell/pen/VBzJXz
$(document).ready(function() {
function cssEncode(name) {
return name.replace(/ /g, "-").toLowerCase();
}
var dataAttr = "data-tab-name";
var tabDivs = $("div[" + dataAttr + "]");
var navTabs = $('<div class="nav nav-tabs">');
var tabContent = $('<div class="tab-content" id="tabs"></div>');
var tabs = [];
var tabPanes = [];
tabDivs.each(function(e) {
var name = $(this).attr(dataAttr);
var encodedName = cssEncode(name);
tabs.push(
'<li><a data-toggle="tab" href="#' +
encodedName +
'">' +
name +
"</a></li>"
);
var tabPane = $(
'<div class="tab-pane fade" id="' + encodedName + '"></div>'
).append($(this).html());
tabPanes.push(tabPane);
$(this).detach();
});
navTabs.append(tabs.join(""));
tabContent.append(tabPanes);
var tabsContainer = $('<div class="tabs"></div>');
tabsContainer.append(navTabs);
tabsContainer.append(tabContent);
$(".iseo-item-page .col-md-12").append(tabsContainer);
$(".nav-tabs a:first").tab("show");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row iseo-item-page">
<div class="col-md-12">
<div data-tab-name="Description">
Content 0
</div>
<div data-tab-name="Video">
Content 1
</div>
<div data-tab-name="Reviews">
Content 2
</div>
</div>
</div>
</div>
The main issue is that when you do it dynamically like you do the li elements all get class of active but it should be only one active. Look # the example your provided as a working one inspect element on the tabs ... you will see that once you select a an tab/li it would get the active class and the previous one would loose it. In your example that class gets set to all so you can't again click on them.
Here is a working version with basically going around bootstrap js:
$(document).ready(function() {
function cssEncode(name) {
return name.replace(/ /g, "-").toLowerCase();
}
var dataAttr = "data-tab-name";
var tabDivs = $("div[" + dataAttr + "]");
var navTabs = $('<div class="nav nav-tabs">');
var tabContent = $('<div class="tab-content" id="tabs"></div>');
var tabs = [];
var tabPanes = [];
tabDivs.each(function(e) {
var name = $(this).attr(dataAttr);
var encodedName = cssEncode(name);
tabs.push(
'<li><a data-toggle="tab" href="#' + encodedName + '">' + name + "</a></li>"
);
var tabPane = $(
'<div class="tab-pane fade" id="' + encodedName + '"></div>'
).append($(this).html());
tabPanes.push(tabPane);
$(this).detach();
});
navTabs.append(tabs.join(""));
tabContent.append(tabPanes);
var tabsContainer = $('<div class="tabs"></div>');
tabsContainer.append(navTabs);
tabsContainer.append(tabContent);
$(".iseo-item-page .col-md-12").append(tabsContainer);
$('a[data-toggle="tab"]').on('click', function (e) {
e.preventDefault();
$(this).parent().addClass("active");
$('li').not(this.parentNode).removeClass('active')
$('.iseo-item-page div').removeClass('active in')
$(this.hash).addClass('active in')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row iseo-item-page">
<div class="col-md-12">
<div data-tab-name="Description">
Content 0
</div>
<div data-tab-name="Video">
Content 1
</div>
<div data-tab-name="Reviews">
Content 2
</div>
</div>
</div>
</div>

Not able to updating dynamic list of checkboxes

Can someone help me, what should I do to refresh the drop down list that appears on Remove Locations page. It is populated from localstorage.city.
Click on 'Open Panel' then click on Remove Locations. Here you will see a list of cities that I added by clicking on Add Locations button.
Delete some locations and then click on Remove locations button. You will notice that previously deleted locations still exists.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8" /> <!-- came from cordova -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js" data-semver="2.1.3" data-require="jquery"></script>
<script>
var SectedCityCode, URL, prov;
$(document).bind('mobileinit',function(){
$.mobile.pushStateEnabled = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- <script src="js/cities.js"></script> -->
<script>
$(document).on("pagecreate", function() {
// Save settings
$( "#myPanel" ).panel({
beforeopen: function( event, ui ) {}
});
$( "#myPanel" ).on( "panelbeforeopen", function( event, ui ) {} );
$("#myPanel").on("panelclose", function(event, ui) {
if (typeof(Storage) !== "undefined") {
localStorage.adl = $("#checkbox-h-2a").is(":checked");
}
});
$('#btnDelCity').click(function() {
var list = '';
$("#delcity input:checkbox:not(:checked)").each(function() {
if (list == '')
list = $(this).val();
else
list = list + ',' + $(this).val();
});
//localStorage.clear();
localStorage.city = list;
alert(localStorage.city);
$.mobile.changePage("#home", { reloadPage: true });
//$.mobile.navigate( "#home" );
});
$('#btnRemoveCity').click(function() {
$.mobile.changePage("#delLocations", { reloadPage: true });
//$.mobile.navigate( "#home" );
});
});
</script>
</head>
<body>
<!-- Start of first page -->
div data-role="page" id="home">
<div data-role="panel" id="myPanel" data-display="overlay">
<!-- panel content goes here -->
<fieldset data-role="controlgroup" data-type="horizontal">
<input name="checkbox-h-2a" id="checkbox-h-2a" type="checkbox">
<label for="checkbox-h-2a">Auto Detect Location</label>
Add Locations
Remove Locations
</fieldset>
</div><!-- /panel -->
<div data-role="header">
<h1>Test</h1>
Open Panel
</div><!-- /header -->
<div data-role="content">
<div data-role="main" class="ui-content">
<p>content will go here</p>
</div>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- end of first page -->
<div data-role="page" id="addLocations" data-cache="false">
<div data-role="header">
<h1>Add Locations</h1>
Home
</div>
<div data-role="main" class="ui-content">
<form class="ui-filterable">
<input id="myFilter" data-type="search">
</form>
<ul data-role="listview" data-filter="true" data-input="#myFilter" id="citynames">
</ul>
</div>
<div data-role="footer">
<h1>Locations Footer</h1>
</div>
<script>
$(document).on('pagebeforecreate', '#addLocations', function(){
var cities = [{
"code": "s0000768",
"englishnames": "City 1"
}, {
"code": "s0000001",
"englishnames": "City 2"
}, {
"code": "s0000404",
"englishnames": "City 3"
}];
//bind cities to addLocations
cities.sort(function(a, b) {
return a.englishnames.localeCompare(b.englishnames);
});
$.each(cities, function(i, obj) {
$("#citynames").append("<li data-name='" + obj.englishnames + "'>" + obj.englishnames + "</li>");
});
/* delegation */
//localStorage.clear();
$("#citynames").on("click", "li", function() {
if (localStorage.city == '')
localStorage.city = $(this).attr('data-name');
else
localStorage.city = localStorage.city + ',' + $(this).attr('data-name');
alert(localStorage.city);
});
});
</script>
</div>
<div data-role="page" id="delLocations">
<div data-role="header">
<h1>Remove Locations</h1>
Home
</div>
<div data-role="main" class="ui-content">
<form id='delcity'>
</form>
</div>
<div data-role="footer">
<h1>Locations Footer</h1>
</div>
<script>
//$(document).on('pagebeforeshow', '#delLocations', function(){
$(document).on('pagebeforecreate', '#delLocations', function(){
if (typeof(Storage) !== "undefined") {
if (!(localStorage.city == '')){
alert("about to create checkboxes");
var savedCities = localStorage.city;
alert(savedCities);
var arr = [];
arr.length = 0;
$("#delcity").trigger('reset');
$("#delcity").empty();
arr = savedCities.split(',');
$.each(arr, function(i, val){
$("#delcity").append("<label><input id='chk" + i + "' type='checkbox' value='" + val + "'>" + val + "</label>");
});
$("#delcity").append("<a href='#delLocations' id='btnDelCity' class='ui-btn'>Remove</a>");
}
}
});
</script>
</div>
</body>
</html>
https://jsfiddle.net/dLsLo94r/13/
Joe
pagebeforecreate only runs once not each time you visit the page. For the delete page you can use pagebeforeshow to rebuild the list of cities each time you visit the page.
$(document).on('pagebeforeshow', '#delLocations', function() {
$("#delcity").empty();
if (typeof(Storage) !== "undefined") {
if (!(localStorage.city == '')) {
var savedCities = localStorage.city;
arr = savedCities.split(',');
$.each(arr, function(i, val) {
$("#delcity").append("<label><input id='chk" + i + "' type='checkbox' value='" + val + "'>" + val + "</label>");
});
$("#delcity").append("<a href='#delLocations' id='btnDelCity' class='ui-btn'>Remove</a>").enhanceWithin();
}
}
});
Then use event delegation for the click event on the delete button as it is created dynamically:
$(document).on("click", '#btnDelCity', function() {
var list = '';
$("#delcity input:checkbox:not(:checked)").each(function() {
if (list == '')
list = $(this).val();
else
list = list + ',' + $(this).val();
});
localStorage.city = list;
alert(localStorage.city);
$.mobile.navigate( "#home" );
});
Updated DEMO

How can I list posts dynamically using jquery and json api?

I want to retrieve posts from my site web with JSON API, and I tried more codes but no data displaying. Where is the problem?
HTML:
<div data-role="page" id="searchPage" >
<div data-role="header" data-position="fixed">
<h1>News</h1>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true" id="searchFood"></ul>
</div>
JS:
$(document).on("pageinit", "#searchPage", function(){
$.getJSON("http://www.maan-lagh.com/?json=get_recent_posts", function(data){
var output = '';
$.each(data, function (index, value) {
output += '<li>' + value.title + '</li>';
});
$('#searchFood').html(output).listview("refresh");
});
});

Having same page footer when open RSS pages

When I click on RSS items in my mobile app, I would like to see same page footer as I have in my first page. I've created my app using Cordova 4.3.0, jQuery mobile and read RSS feeds using jQuery in my onDeviceReady() function in index.js file as follow:
onDeviceReady: function () {
$(function () {
$.get('http:myRssUrl.cshtml',function(data) {
var $XML = $(data);
var html = '';
$XML.find("item").each(function() {
var $this = $(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text(),
description: $this.find("description").text(),
pubDate: $this.find("pubDate").text(),
author: $this.find("author").text(),
enclosure: $this.find("enclosure").attr('url'),
};
html +=
'<a class="result-link" title=" " style="text-decoration: none" href="' + item.link + '" style="font-size: 11px" >' +
'<div class="result-image">' +
' <figure>' +
'<img src="' + item.enclosure + '" style="display: block;"></img>' +
'</figure>' +
'</div>' +
'<div class="alltext" style="padding-right: 5px;">' +
'<h3 class="result-title">' + item.title +'</h3>' +
'<div class="result-description">' + item.description +'</div>' +
'</div></a>'
});
jQuery('#result').html(html);
});
});
app.receivedEvent('deviceready');
}
I also have my footer navigation bar in footer.html file which will be loaded in index.html file as follows:
<script>
$(document).on('pageinit', "#index", function (event, ui){
$("#" + event.target.id).find("[data-role=footer]").load("pages/footer.html", function(){
$("#" + event.target.id).find("[data-role=navbar]").navbar();
});
});
</script>
<body>
<div data-role="page" class="app" id="index">
<div data-role="header" data-position="fixed" data-id="main-header" id="header">
<div data-role="navbar" class="ui-btn-active ui-state-persist">
<ul>
<li>
</li>
<li></li>
</ul>
</div><!-- /navbar -->
</div><!-- /header -->
<div data-role="content" data-theme="d" id="deviceready">
<div id="result" data-role="listview">
</div>
</div><!-- /content -->
<div data-role="footer" data-position="fixed" data-id="main-footer" id="footer">
</div><!-- /footer -->
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
My problem is that I can't load my page footer navbar in my RSS pages, I saw some relevant examples about it and applied different approaches, but still have the same problem.

Show Post Title on Header

each time I click on a Post link I want the Title of the Post to appear on the Header page. See screen shot
As seen, I would like the 'Devotional Message' replaced by the Post Title...
HTML Code:
<div id="devotionpost" data-role="page">
<div data-role="header" data-position="fixed" data-theme="a">
<h1>Devotional Message</h1>
Devotion
</div><!-- header-->
<div data-role="content">
<div id="mypost"> </div>
</div><!-- content -->
</div><!-- page -->
JS Code:
function showPost(id) {
$.getJSON('http://howtodeployit.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
});
function showPost(id) {
$("#devotionpost h1").html("");// to empty previous title
$.getJSON('http://howtodeployit.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
$("#devotionpost h1").html(data.post.title);// by this 'Devotional Message' replaced by the Post Title..
});

Categories