Dynamically Populate JQUERY Mobile Multi-Page Page - javascript

JQUERY Mobile Beginner Question: I have two pages in my simple multi-page JQUERY Mobile 'App'. When the user navigates to PAGE2, I want to do an AJAX call to get a JSON object containing a list of people + DB ID pairs. I want to present the list of people as buttons on PAGE2.
Code Snippet:
<div id="PAGE2" data-role="page">
<div class="ui-content">
// I want buttons to appear sequentially here
</div>
</div>
PAGE2 is my "placeholder" to populate with:
<input type="button" id="id1" name="id1" value="Bob Smith"/>
<input type="button" id="id2" name="id2" value="Jane Doe"/>
<input type="button" id="id3" name="id3" value="Kayla Kaye"/>
I'd also need to add a 'click' event handler in the script to react to the buttons. The reaction will be the same for all buttons (dynamically populate a PAGE3 with people detail, but I think I can figure that out if I see how PAGE2 population is correctly handled). What is the proper way to go about dynamically "creating" PAGE2 using the skeleton in place?

if jquery is allowed:
var elements = { id1:'Bob Smith', id2:'Jane Doe', id3:'Kayla Kaye'};
$.each( elements, function( key, value ) {
$("#PAGE2 .ui-content").append('<input type="button" id="' + key + '" name=" + key " value " + value +'"/>');
}

You can try this
$('#PAGE2').on('pagebeforeshow', function(){
var people = [
{ name:'Bob Smith', age:'56', place:'London'},
{ name:'John', age:'65', place:'USA'},
];
var btns;
$.each(people,function(indx,ppl){
btns = btns + '<input type="button" name="id1" value="' + ppl.name +'"/>';
});
$('#content_div').html(btns);
});
set id to div content to content_div

Here is a DEMO
With your 3 pages setup like this (I have added container divs for the buttons and details):
<div data-role="page" id="PAGE1">
<div data-role="header">
<h1>PAGE 1</h1>
</div>
<div role="main" class="ui-content">
Go to page 2
</div>
</div>
<div data-role="page" id="PAGE2">
<div data-role="header">
<h1>PAGE 2</h1>
</div>
<div role="main" class="ui-content">
<div id="thePeople"></div>
</div>
</div>
<div data-role="page" id="PAGE3">
<div data-role="header">
<a data-rel="back" class="ui-btn ui-btn-icon-left ui-icon-back">Back </a>
<h1>PAGE 3</h1>
</div>
<div role="main" class="ui-content">
<div id="theDetails"></div>
</div>
</div>
You can use the pagecontainer widget's beforeshow event to make your ajax call:
http://api.jquerymobile.com/pagecontainer/#event-beforeshow
In my example, I am checking where you are coming from and where you are going to. So coming from PAGE1 to PAGE2, I make the AJAX call and create the buttons. But if returning from PAGE3 to PAGE2, I just leave the already created buttons alone. Ater adding the buttons to the page, make sure and call .enhanceWithin() on the container so that jQM enhances the buttons.
$(document).on( "pagecontainerbeforeshow", function( event, ui ) {
var prevID = ui.prevPage.prop("id");
var newID = ui.toPage.prop("id");
if (prevID == "PAGE1" && newID == "PAGE2") {
//we have come from page 1 to page 2, so make AJAX call and populate page 2
var data = [
{ "id": "id1", "name":'Bob Smith'},
{ "id": "id2", "name":'Jane Doe'},
{ "id": "id3", "name":'Kayla Kaye'},
];
var buttons = '';
$.each(data, function(indx){
buttons += '<input type="button" name="' + this.id + '" value="' + this.name +'"/>';
});
$("#thePeople").empty().append(buttons).enhanceWithin();
}
});
Finally, when PAGE2 is created, I use event delegation to create a click event for any buttons that might be added (with event delegation, the buttons don't have to exist at the time the event is bound). In the event, get the id/name for the button that is clicked, get the details (Another AJAX call?), populate PAGE3, and then navigate to PAGE3 using the pagecontainer widget change method:
http://api.jquerymobile.com/pagecontainer/#method-change
$(document).on("pagecreate","#PAGE2", function(){
$(document).on('click', '#thePeople input[type="button"]', function(e){
var personid = $(this).prop("id");
var name = $(this).val();
$("#theDetails").text('Details for ' + name);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#PAGE3", { transition: "slide" });
});
});
DEMO

Related

how to use javascript event handler

I have a 2 col layout, on the left i have a button that says show code and on the right i have some html.
The above is repeat numerous time so i have a list of buttons that i want related to the "widget" next to it.
If i click on each button, i would like to show the innerHTML of the element to the right in an alert box.
My right column html widgets are a class called "mywidgets", and my buttons to the left have a class called "showcode"
how would I go about showing the code of the related box to the right on click of button to the left in javascript or jquery?
if I do something like:
var showthem = document.getElementsByClassName('mywidgets');
for (var i=0; i < widgetBits.length; i++) {
};
but I get confused on how to count each button and each class in the seperate area, then show the code on click.
I was also thinking about something similar to below but again I get confused on how to utilize "this"/each item clicked.
$(document).ready(function(){
$("button").click(function(){
$("mywidgets").clone().appendTo("myareofchoce");
});
});
HTML:
left area :
<div class="container marginBTM10">
<div class="row">
<div class="col-lg-offset-2 col-md-offset-2 col-lg-10 col-md-10 bgColor_FFF padding10">
<h2>Widget 1</h2>
<div class="highlight">
<button class="btn btn-primary btn-sm " onclick="widgets()">get code</button>
right hand area :
<div class="col-lg-4 col-md-4">
<!-- widget 1 starts-->
<div class="sortable bgColor_FFF mywidgets">
<div class="padding10">
stuff
</div>
</div>
<!-- widget 1 ends-->
</div>
</div>
http://jsfiddle.net/wne6rnda/1/
to connect buttons and widgets must be used in a single tag.
in this case: widget has id and corresponding button has data-id with same value
HTML:
buttons:
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets1">
...
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets2">
...
widgets:
div class="sortable bgColor_FFF mywidgets" id="mywidgets1">
...
div class="sortable bgColor_FFF mywidgets" id="mywidgets2">
...
JQ
$('.get_class').click(function () {
//get id of selected widget
var id = $(this).data('id');
//get selected widget
var $widget = $(id);
//clon and add selected widget
$widget.clone().appendTo(".myareofchoce");
})
UPDATE: 2
http://jsfiddle.net/wne6rnda/9/
$('.get_class').click(function () {
var id = $(this).data('id');
var $widget = $(id);
var html=$widget.html();
//solution 1 - output to the textarea
var txt=$(".myareofchoce2").val();
$(".myareofchoce2").val(txt+"\r\n"+html);
//solution 2 - use <xmp> tag
html='<xmp >'+html+'</xmp >';
$(".myareofchoce").append(html);
})

how to change values in a hidden chunk of html code

I have this hidden block of code that i want to call based on the values that are received from server:
<div id="hiddenChart" style="display:none;">
<li style="height:auto;">
<div class="col-sm-4" id="chart_0_0">
<div class="panel panel-success" style="width:550px; height:auto;" id="accordion_0_0">
<div class="panel-heading">
<div class="btn-group" style="float:right;">
<i class="glyphicon glyphicon-minus" id="minimize_0_0"></i>
<i class="glyphicon glyphicon-remove" id="close_0_0"></i>
</div>
<h3 class="panel-title">title</h3>
</div>
<div class="panel-body" style="height:400px;">
<nvd3-multi-bar-chart data="Sec1Graf1Data" id="dataChart_0_0" height="400" showXAxis="true" reduceXTicks="true" showYAxis="true" showLegend="true" showControls="true" tooltips="true">
<svg></svg>
</nvd3-multi-bar-chart>
</div>
</div>
</div>
</li>
</div>
but i need to change some values: ids, tags, data variables.
I know how to show the code using "$('ul').append($('div').html());" but i have to change it before doing it.
How can i do it?
How do i define in which fields i have to insert the string i'me receiving?
Thk
UPDATE:
I was able put it to work, here is the fiddle with it fiddle.
When i inspect the element, the ids that i want to change, instead of #1, it returns chart_0_0.
Thank you all for your posts and help
You can get a reference to your div like this:
var $div = $('#hiddenChart');
To clone it,
var $clonedDiv = $div.clone();
Then, in the $cloneDiv object, you make the changes:
$clonedDiv.find(--selector of a node--).attr(atributeName, atributeValue); //change/add attribute
$clonedDiv.find(--selector of a node--).removeAttr(atributeName); //remove attribute
And so on. I won't explain how jQuery works, Lekhnath gave you a link.
Finally you insert the $clonedDiv with .appendTo() wherever you want. The original div remains untouched so you can clone it again and again.
Jquery Change text/html from a hidden div content :
Simple
maintain a copy of the hidden content
replace the content based on the element class/id selector with the server response
then paste the html into another div
replace the content of the hidden back to original (optional)
http://jsfiddle.net/austinnoronha/ZJ3Nt/
$(document).ready(function(){
var serverRes = {
title: "New Title In Header",
body: "New body text from server <\/br><nvd3-multi-bar-chart data=\"Sec1Graf1Data\" id=\"dataChart_0_0\" height=\"400\" showXAxis=\"true\" reduceXTicks=\"true\" showYAxis=\"true\" showLegend=\"true\" showControls=\"true\" tooltips=\"true\"><svg><\/svg><\/nvd3-multi-bar-chart>"
};
var tmpOldCont = $("#hiddenChart").html();
var counter = 1;
$(".serverres").click(function(){
$("#hiddenChart").find(".panel-body").html(counter + " = " + serverRes.body);
$("#hiddenChart").find(".panel-title").text(serverRes.title + " " + counter);
counter++;
$(".box-container").html($("#hiddenChart").html());
$("#hiddenChart").html(tmpOldCont);
});
});

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

phonegap chat application user can see others message

I am using phonegap to develop an one to one chat application. My problem is when user click a contact and send a message. Then user click go back button and click another contact it can still see the message which he just sent to the first user.
Here is a part of my code:
Here is using ajax to get contact from server.When it success,it will generate a list view to show all contacts.
$.each(contacts, function(i,item)
{
output += '<li data-name='+item+'>' + item + '</li>';
$('#contacts_list').html(output).listview('refresh');
//Show the contact name on the front of chat page
$('#contacts_list').children('li').on('click', function ()
{
var contact_name=$(this).attr('data-name');
$('#contact_name').html(contact_name);
get_name(contact_name);
});
});
<!--When someone click a user in contacts, it will show the chat page-->
<div data-role="page" id="chat_page" data-role="page" data-theme="a">
<div data-role="header">
<h1 id="contact_name"></h1>
</div>
<div data-role="content">
<div id="incomingMessages" name="incomingMessages" class="msgContainerDiv" >
</div>
<label for="messageText"><strong>Message:</strong></label>
<textarea id="messageText"></textarea>
</div>
<div data-role="footer">
<fieldset class="ui-grid-a">
<div class="ui-block-a">
Go Back
</div>
<div class="ui-block-b">
<button data-theme="a" id="chatSendButton" name="chatSendButton">Send
</input>
</fieldset>
</div>
</div>
And here is part of ajax code where I using ajax to get chat data, then append them in to my chat page.
success: function(data)
{
var get_data = JSON.parse(data);
$("#incomingMessages").append
(
"<div class='message'><span class='username'>" +
(get_data.from || 'Anonymous') +"</span> : " +
(get_data.message || ' ') + "</br>" +
(get_data.message_time || ' ')
+"</div>"
);
}
});
I know the reason is when user click contact it will always go to the same page and that is why message can be seen to all of users.
Is there any solution for this?
Thanks in advance.
A simple solution will be to use local storage to store the history (#incomingMessages) and #messageText for each user.
Then you can clear #messageText and just reload it when the user reopens the chat.
You should clear #incomingMessages when you switch users. You are likely leaving the HTML content in that div when you want to be replacing it with the new user's messages.
Something like
$('#incomingMessages').html('')

Javascript functions overlapping

I have two functions that happen when a link is clicked, a box drops down.
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('login')"class='regular' name='save'> Log In </div></a>
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('register')" class='regular' name='save'> Register</div></a><br><br>
<div class = "Interactlogin" id = "login"> Login</div>
<div class = "Interactlogin" id = "register"> Logina</div>
When login is clicked, the log in box slides down, but then when the register box is clicked, the login box slides further to accommodate for the register box whereas i would like only one box to be shown at a time.
Any help is appreciated.
function toggleInteractlogin(x)
{
if($('#' + x).is(":hidden"))
{
$('#'+x).slideDown(200);
}
else
{
$('#'+x).hide();
}
$('Interactlogin').hide();
}
I have updated the solution in LIVE DEMO - JSFiddler
HTML
<div class='buttons'>
<a id="btnlogin" href= '#' class='login' name='save'>Log In </a>
</div>
<div class='buttons'>
<a id="btnregister" href='#' class='regular' name='save'>Register</a>
</div><br><br>
<div class="Interactlogin" id="login" style="display:none">Login</div>
<div class="Interactlogin" id="register" style="display:none">Logina</div>​
JS
$('#btnlogin').click(function(){
$('#login').show();
$('#register').hide();
});
$('#btnregister').click(function(){
$('#login').hide();
$('#register').show();
});
​
make sure you slide up the register box first when login button is clicked, similarly make sure you slide up the login button first when when register button is clicked
so for loginn button click
1 slide up the register box
2 then slide down the login box
similarly for register
1 slide up the login box
2 then slide down the register box.
try specifying different ids to login & register button
function toggleInteractlogin(x)
{
if(x=='register')
{
$('#login').hide();
$('#register').show();
}
else
{
$('#register').hide();
$('#login').show();
}
}
for show/hide you can specify different effect as well like fadein/fadeout
You can simplify this a bit using this revised markup:
<div class='buttons'><a href='#' class='login'>Log In</a></div>
<div class='buttons'><a href='#' class='register'>Register</a></div>
<br><br>
<div class = "Interactlogin" id = "login">Login</div>
<div class = "Interactlogin" id = "register">Logina</div>
$('.login,.register').mousedown(function() {
$('.Interactlogin').hide();//hide them all initially
var myType = $(this).attr('class');//assumption this is the only class
$('#' + myType).slideDown(200);
});
I assume this CSS to hide initially:(yours may differ)
.Interactlogin{display:none;}

Categories

Resources