I'm learning how to use onsen.io and the best way to learn is by making a Pokemon app!
But of course, being a noob, I'm having trouble trying to loop through my list of 151 Pokemons using onsen.io. I'm able to console.log the list of 151, but I'm not sure what's missing to display it in an ons-list.
Am I looping it incorrectly?
Thanks!
Here's my code:
<ons-navigator id="myNavigator" page="main-temp"></ons-navigator>
<!-- ******************** main-template ******************** -->
<template id="main-temp">
<ons-page id="main-page">
<ons-toolbar style="background-color: red;">
<div class="center" style="color: #fff;">Pokedex</div>
</ons-toolbar>
</ons-page>
</template>
<!-- ******************** list template ******************** -->
<template id="list-temp">
<ons-page id="list-page">
<div class="content content-container">
<ons-list id="list-item"></ons-list>
</div>
</ons-page>
</template>
<!-- ******************** spinner modal ******************** -->
<ons-modal id="spinner-modal">
<div style="margin: auto;">
<ons-icon icon="md-spinner" size="100px" spin></ons-icon>
</div>
</ons-modal>
window.onload = function (){
var spinnerModal = document.querySelector('#spinner-modal');
spinnerModal.show();
var settings = {
"url":`https://pokeapi.co/api/v2/pokemon?limit=151`,
"method": "GET",
"timeout": 0,
};
$.ajax(settings)
.done(function(result){
sendData(result);
let results = result;
console.log(results);
})
.fail(function(xhr, status, error){
console.log('error:' + xhr.status);
})
.always(function(){
spinnerModal.hide();
})
function sendData(jsonData){
var itemsList = document.getElementById('list-item');
for(let i = 1; i < jsonData.length; i++){
itemsList.appendChild(
ons.createElement(
'<ons-card class="inside-cards">'+
'<ons-list>' +
'<ons-list-item modifier="tappable>' +
'<div class="left" >' +
jsonData[i].name +
'</div>' +
'<div class="" style="margin-left:20px;" >' +
'<ons-icon icon="fa-hashtag"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-thumbs-up"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-user"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'</div>' +
'<div>' +
'</div>' +
'</ons-list-item>' +
'</ons-list>' +
'</ons-card>'
)
);
}
}
}
there are two problems in your code.
your api response contains result but you want list of pokemons which is avaialble in result.results so you need to call sendData(result.results)
you are using template tag which creates a different document scope called documentFragment. also in template the id means the HTML page you want to render in app as template so id should be defined as id='something.htm'. for more details read ons-template
proper use of template
<template id="page.html">
</template>
or
<ons-splitter>
<ons-splitter-content page="page.html">
</ons-splitter-content>
</ons-splitter>
showing this in online editor is a bit difficult since online editor provide only one HTML. let me see if I get time to do this in plunkr/stackblitz online editor or I hope you figure out this from ons documentation.
ons.ready(function() {
var spinnerModal = document.querySelector('#spinner-modal');
spinnerModal.show();
var settings = {
"url": `https://pokeapi.co/api/v2/pokemon?limit=151`,
"method": "GET",
"timeout": 0,
};
$.ajax(settings)
.done(function(result) {
sendData(result.results); // result.results contains pokemon list :)
let results = result;
console.log(results);
})
.fail(function(xhr, status, error) {
console.log('error:' + xhr.status);
})
.always(function() {
spinnerModal.hide();
})
function sendData(jsonData) {
debugger;
var itemsList = document.getElementById('list-item'); // this is no longer null since this is no longer part of template.
for (let i = 1; i < jsonData.length; i++) {
itemsList.appendChild(
ons.createElement(
'<ons-card class="inside-cards">' +
'<ons-list>' +
'<ons-list-item modifier="tappable>' +
'<div class="left" >' +
jsonData[i].name +
'</div>' +
'<div class="" style="margin-left:20px;" >' +
'<ons-icon icon="fa-hashtag"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-thumbs-up"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-user"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'</div>' +
'<div>' +
'</div>' +
'</ons-list-item>' +
'</ons-list>' +
'</ons-card>'
)
);
}
}
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css">
<link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">
<script src="https://unpkg.com/onsenui/js/onsenui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<ons-navigator id="myNavigator" page="main-temp"></ons-navigator>
<!-- ******************** main-template ******************** -->
<template id="main-temp">
<ons-page id="main-page">
<ons-toolbar style="background-color: red;">
<div class="center" style="color: #fff;">Pokedex</div>
</ons-toolbar>
</ons-page>
</template>
<!-- ******************** list template ******************** -->
<ons-page id="list-page">
<div class="content content-container">
<ons-list id="list-item"></ons-list>
</div>
</ons-page>
<!-- ******************** spinner modal ******************** -->
<ons-modal id="spinner-modal">
<div style="margin: auto;">
<ons-icon icon="md-spinner" size="100px" spin></ons-icon>
</div>
</ons-modal>
</body>
</html>
Related
for(var key in result)
{
var html = '';
html += '<li class="item item_chat">' +
'<div class="product-img">' +
'<img src="' + base_url + '/assets/img/noimage.png" alt="Product
Image" class="img-size-50">' +
'</div>' +
'<div class="product-info">' +
'<a href="javascript:void(0)" onclick="viewGroupBody(this,' +
result[key].id + ',' + result[key].name + ');" class="product-
title">' + result[key].name +
'<span class="badge badge-danger float-right"> Group </span></a>' +
'<span class="product-description"> Message </span>' +
'</div>' +
'</li>';
$('#messageListDashGroups').append(html);
}
I am getting error on this line in onclick function
'<a href="javascript:void(0)" onclick="viewGroupBody(this,' +
result[key].id + ',' + result[key].name + ');" class="product-
title">' + result[key].name +
Before i use two arguments
onclick="viewCusBody(this,' + id + ')"
But now i add an extra argument so i am having issue
You can try with Template literals.
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Demo:
var base_url = "test.com";
var result_id = "some_id";
var result_name = "jhon";
var html = `<li class="item item_chat">
<div class="product-img">
<img src="${base_url}/assets/img/noimage.png" alt="Product
Image" class="img-size-50">
</div>
<div class="product-info">
<a href="javascript:void(0)" onclick="viewGroupBody(this,'${result_id}','${result_name}');" class="product- title">${result_name}
<span class="badge badge-danger float-right"> Group </span></a>
<span class="product-description"> Message </span>
</div>
</li>`;
$('#messageListDashGroups').append(html);
function viewGroupBody(el, id, name){
console.log(id)
console.log(name);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="messageListDashGroups"></div>
For IE: Try the traditional way by changing
onclick="viewGroupBody(this,' + result[key].id + ',' + result[key].name + ');"
To
onclick=viewGroupBody(this,"'+result['key'].id+'","'+result['key'].name+'")
var base_url = "test.com";
var result = {key:{id: "some_id", name:"john"}};
var html = '';
html += '<li class="item item_chat">' +
'<div class="product-img">' +
'<img src="' + base_url + '/assets/img/noimage.png" alt="Product Image" class="img-size-50">' +
'</div>' +
'<div class="product-info">' +
'<a href="javascript:void(0)" onclick=viewGroupBody(this,"'+result['key'].id+'","'+result['key'].name+'"); class="product- title">'+
'<span class="badge badge-danger float-right"> Group </span></a>' +
'<span class="product-description"> Message </span>' +
'</div>' +
'</li>';
$('#messageListDashGroups').append(html);
function viewGroupBody(el, id, name){
console.log(id)
console.log(name);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="messageListDashGroups"></div>
I'm trying to fade out and fade in a card element. My html looks like this:
<form class=" mt-4 mw-800 center-block animated fadeInUp">
<div class="row">
<div class="col-lg-12 content">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">{{ $random_idea->title }}</h3>
</div>
<div class="card-body">
{{ $random_idea->description }}
</div>
</div>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button id="idea" type="button" class="btn btn-raised btn-primary btn-block">
Geef mij een ander idee</button>
</form>
My jQuery code looks like this:
$( "#idea" ).click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$.ajax({
type: "POST",
url: "/idea",
success: function(response) {
$(".card").fadeOut();
$('<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description +
'</div>' +
'</div>').appendTo('.content').fadeIn();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
The card div is fading out and fading in. But there is a delay, it's not shown good.
My lay-out looks like this:
When you click on the button the card fades out and another card fades in. But it's not smooth. Do you have any ideas to help me?
jQuery fadeIn() and fadeOut() are asynchronous. So, the new and old elements are fading in/out together. But, those methods gets a callback will call after the animation. So, you can rewrite your success function as follows:
$(".card").fadeOut(function() {
$(this).remove();
$('<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description + '</div>' +
'</div>').appendTo('.content').fadeIn();
});
Try using this
var html = '<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description +
'</div>' +
'</div>';
$(html).hide().appendTo(".content").fadeIn(300);
The reason its not going smooth is because you didnt give a speed within your fadeout/fadein function.
If you read the docs on https://www.w3schools.com/jquery/eff_fadeout.asp you notice the syntax accepts a speed $(selector).fadeOut(speed,easing,callback)
Wenn you fill in the speed of your fadein() and your fadeout() it should go smooth.
I want to add the HTML of a column into a row, and have 3 columns per row. I do not wish to display all of the images in my array, and if they are not supposed to be displayed, I do not wish for the column number to tick over.
This should be really easy, but I'm getting really confused. My current code is just giving me an infinite loop getting stuck on an image where it is not supposed to display.
function loadImages()
{
var data = <?php echo json_encode($data); ?>;
data = $.map(data, function(value, index) {
return [value];
});
console.log(data);
for(var i = 0; i < data.length; i++)
{
data[i] = $.map(data[i], function(value, index) {
return [value];
});
}
var div = document.getElementById('imageBox');
var img = 0;
var row = 0;
while(img < data.length)
{
div.innerHTML += '<div class="row gallery-row" id="row' + row + '"></div>';
var col = 0;
while(SOMETHING OR OTHER)
{
if(!!data[img])
{
var html = [
'<div class="col-sm-4">',
' <a data-toggle="modal" data-target="#imageModal" onclick="" href="#" id=a' + img + '>',
' <img class="img-responsive img-gallery" src="" id=img' + img + '>',
' </a>',
'</div>'
].join('');
var valid = data[img][1][4].split(": ")[1];
if(valid == "True")
{
var imgName = data[img][0];
var name = data[img][1][0];
var location = data[img][1][1];
var desc = data[img][1][2];
document.getElementById('row'+ String(row)).innerHTML += html;
document.getElementById('img' + String(img)).setAttribute('src', imgName);
document.getElementById('a' + String(img)).setAttribute('onclick', "javascript:loadModalImage('" + imgName + "', '" + name + "', '" + location + "', '" + desc + "')");
col++;
}
img++;
}
}
row++;
}
}
function loadImageData(imageName, imageLocation, imageDesc)
{
var imgName = document.getElementById('img-name');
var imgDesc = document.getElementById('img-desc');
imgName.innerHTML = "Taken by <b>" + imageName + "</b> at <b>" + imageLocation + "</b>.<br>";
imgDesc.innerHTML = imageDesc;
}
function loadModalImage(image, imageName, imageLocation, imageDesc)
{
var modalImage = document.getElementById('imageModalImage');
modalImage.setAttribute("src", image);
loadImageData(imageName, imageLocation, imageDesc);
}
And the HTML:
<div class="box" name="box" id="imageBox">
<!-- Modal -->
<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-img">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<img class="img-responsive imageModalImage" id="imageModalImage" src="">
<p id="img-name"></p>
<p id="img-desc"></p>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
As I said, I'm sure this should be an easy fix. Any help is still greatly appreciated, as I've just completely confused myself trying to solve this.
Looking for a starting point. I'm getting my data (via json) for a JQM page. I need to be able to edit any of the returned result fields and UPDATE the database via .post json.
My thought is to iterate through the json array, make changes and post json array back, should I be populating text-boxes in the initial load and then creating separate array?
$.getJSON('JSON_MDB.php',
function (data) {
// data is now JSON object instantiated from retrieved info
$.each( data, function ( i, val ) {
($('<div>')
.attr({
'data-role': 'collapsible',
'data-content-theme': 'c',
'data-collapsed': 'true',
'id': 'cResults'
})
.html('<h4>' + this.lastName + ', ' + this.firstName + '</h4><ul data-role="listview" data-filter="true" data-filter-placeholder="Search Choices..." data-inset="true" id="makecollapsibleul"><li>'
+ 'FDID: ' + this.FDID + '</li><li>'
+ 'Choice 1: ' + this.C1 + '</li><li>'
+ 'Choice 2: ' + this.C2 + '</li><li>'
+ 'Choice 3: ' + this.C3 + '</li><li>'
+ 'Choice 4: ' + this.C4 + '</li><li>'
+ 'Choice 5: ' + this.C5 + '</li><li>'
+ 'Choice 6: ' + this.C6 + '</li><li>'
+ 'IP: ' + this.IPADDRESS + '</li><li>'
+ 'Pick Date: ' + this.PICKDATE + '</li></ul>'
))
.appendTo('#primary');
$('#makecollapsible').collapsibleset().trigger('create');
$.mobile.hidePageLoadingMsg();
});
}
);
HTML:
<div data-role="page" id="main">
<div data-role="header">
<h1>MCFRSIT JSON DATA</h1>
</div><!-- /header -->
<div data-role="content">
<ul data-role="listview" id="outer-ul">
<li>
<div data-role="collapsible">
<h4>Submitted Choices</h4>
<ul data-role="listview" data-inset="true" data-filter="true" id="makecollapsible">
<!-- AJAX CONTENT -->
</ul>
</div>
</li>
</ul>
</div><!-- /content -->
<div data-role="footer">
</div>
</div><!-- /page -->
I'm working on a dynamically changing web app. I'm using javascript and jQuery to populate DIV's with <li>'s and <a>'s. For example, I start with one menu dynamically built with javascript. From that menu, depending on item selected, another javascript function gets called to dynamically populate the corresponding DIV. The problem coming when I keep dynamically building submenu's and JQTouch doesn't switch to the next page.
In the following code, the alert('what') displays on an iPhone but never switches to the ePresentationDetails DIV. I have tried forcing it with jQT.goTo(); but that usually causes more issues and doesn't fix the problem.
Basic html code:
<div id="home">
<div class="toolbar">
<a class="blueButton" href="javascript: void(0);" onClick="$('#logout').show();">Logout</a>
<h1>AllaccessMD</h1>
</div>
<div id="logout" style="display:none;">
<div id="confirmBox">
Are you sure?
<a class="logoutButton" href="javascript: void(0);" onClick="logOut();">Logout</a>
<a class="cancelButton" href="javascript: void(0);" onClick="$('#logout').hide();">Cancel</a>
</div>
</div>
<h1>Home</h1>
<ul class="edgetoedge" id="ulHome"></ul>
</div>
<div id="ePresentations">
<div class="toolbar">
<a class="button back" href="#">Back</a>
<h1>AllaccessMD</h1>
</div>
<div id="ePresentationsData"><div class="progress"><font style="padding-right:5px;">Loading...</font><img border="0" src="Images/ajax-loader.gif" /></div>
</div>
</div>
<div id="ePresentationDetails">
<div class="toolbar">
<a class="button back" href="#">Back</a>
<h1>AllaccessMD</h1>
</div>
<div id="ePresentationDetailsData"><div class="progress"><font style="padding-right:5px;">Loading...</font><img border="0" src="Images/ajax-loader.gif" /></div>
</div>
</div>
Javascript file:
function setupHome(){
if(localStorage.role == "Specialist"){
var homeUL = '<li class="arrow"><a id="aEP" rel="s,' + localStorage.userID + '" href="#ePresentations">My E-Presentation</a></li>'
+ '<li class="arrow"><a id="aN" rel="s,' + localStorage.userID + '" href="#date">My Newsletter</a></li>'
+ '<li class="arrow"><a id="aE" rel="s,' + localStorage.userID + '" href="#date">My Events</a></li>'
+ '<li class="arrow"><a id="aMP" rel="s,' + localStorage.userID + '" href="#date">Medical Partners</a></li>'
+ '<li class="arrow"><a id="aS" rel="s,' + localStorage.userID + '" href="#date">Search</a></li>'
+ '<li class="arrow"><a id="aP" rel="s,' + localStorage.userID + '" href="#date">Profile</a></li>';
$('#ulHome').html(homeUL);
} else {
var homeUL = '<li class="arrow"><a id="aMP" rel="m,' + localStorage.userID + '" href="#date">Medical Partners</a></li>'
+ '<li class="arrow"><a id="aS" rel="m,' + localStorage.userID + '" href="#date">Search</a></li>'
+ '<li class="arrow"><a id="aP" rel="m,' + localStorage.userID + '" href="#date">Profile</a></li>';
$('#ulHome').html(homeUL);
}
$('#ePresentations').bind('pageAnimationStart', function (e){setupEPresentations(getID($('#aEP').attr('rel')).id);});
}
function setupEPresentations(sID){
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var epObject = JSON.parse(xmlhttp.responseText);
var html = '<h1>Dr. ' + epObject.DR.DATA[0][1] + ' E-Presentation\'s</h1>';
if(epObject.EP.DATA.length == 0){
html += '<div><p>There are currently no E-Presentation\'s for this doctor.</p></div>';
} else {
html += '<ul class="edgetoedge">';
for(var i in epObject.EP.DATA){
html += '<li class="arrow"><a id="' + epObject.EP.DATA[i][0] + '" href="#ePresentationDetails">' + epObject.EP.DATA[i][1] + '</a></li>';
}
html += '</ul>';
}
$('#ePresentationsData').html(html);
$('#ePresentationsData li a').click(function(e) {alert('what');setupEPresentationDetails(this.id);});
}
}
xmlhttp.open("GET","Lib/ePresentations.cfm?Type=getAllEPsID&sID=" + sID,true);
xmlhttp.send();
}
function setupEPresentationDetails(id){
/*xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var epObject = JSON.parse(xmlhttp.responseText);
var html = '<h1>Dr. ' + epObject.DATA[0][0] + ' E-Presentation</h1>';
html += '<p>';
//html += '<br />' + epObject.DATA[0][2].format("mmmm dd, yyyy");
html += '<br /><strong>Rating:</strong> ' + Math.ceil(epObject.DATA[0][4]) + ' / 5 (' + epObject.DATA[0][5] + ' votes cast)';
html += '<br /><br /><a rel="external" href="http://www.youtube.com/v/' + epObject.DATA[0][3] + '">Click here to view E-Presentation</a>';
html += '</p>';
$('#ePresentationDetailsData').html(html);
}
}
xmlhttp.open("GET","Lib/ePresentations.cfm?Type=getEP&id=" + id,true);
xmlhttp.send();*/
$('#ePresentationDetailsData').html('I dont get called?');
}
What am I doing wrong? Maybe there is a better way to do this?
Thanks!!
What version of JQT are you using?
Are you wrapping your entire app in the <div id="jqt"></div> ?
Have you looked at it using Safari developer mode to see what the list HREFs actually are when they are rendered?
I would look at the rendered HREF for these:
<li class="arrow"><a id="aS" rel="m,' + localStorage.userID + '" href="#date">Search</a></li>
Make sure the html is what it should be. The rel= or your quotes not being escaped might be throwing it off. But I don't see anything obvious that you are doing wrong.
Do you have a link you can send me so I can debug it in action?