Hi i'm creating list view dynamically. I want to get the data of particular row on click, to proceed to further steps.
my code is as below
function getList(tx, results){
$('#DeliveryList').empty();
var len = results.rows.length;
for(var i=0; i <len; i++)
{
var deliveryItems = results.rows.item(i);
var html = '<li data-role="list-divider">'+deliveryItems.DeliveryName+ ' | ' + deliveryItems.PrimaryName+' <span class="ui-li-count">Copay ='+deliveryItems.Total+'</span> </li><li><a><img src="Pending"/><h3>'+deliveryItems.Name1+'</h3><p>'+deliveryItems.Address+'</p><p>'+deliveryItems.City+' <b></b></p><p><strong>'+deliveryItems.ContactNumber+'</strong></p><a href="#PrescriptionPage" class="cls_btn" id="btn_list" onclick = "Prescription()" >Delivary Details</a></a></li>';
$('#DeliveryList').append(html).trigger('create');
}
$('ul').listview('refresh');
}
My html file looks like
<div data-role="page" id="page3" >
<div data-role="header">
Back
<h1>Heading</h1>
Home
</div><!-- /header -->
<ul data-role="listview" id="DeliveryList" data-inset="true" data-theme="d" data-divider-theme="b"> </ul>
</div>
can any one help me to achieve the result. Thanks in Advance.
It worked for me with below code
$('ul').children('li').on('click', function () {
alert('Selected Name=' + $(this).text());
});
You're using jQuery already, why not use it to create these elements aswell? I asume getList() is bound to an event.
// Create the element
var li = $('<li></li>');
// Add your class
li.addClass('list-divider');
// Change the innerHTML
li.html('Your content');
// Then append it to the list
$('#DeliveryList').append(li);
Simply alter this code to your need. This example just adds one <li> element with a class and some content.
Good luck.
Related
lets say i have a parent-div. And in this div-container, i want to display 5 elements which have all the same structure. For example:
<div class="element">
<p class="name">
</p>
<div class="logo">
</div>
</div>
Is there a way to make an object or prototype out of it, so i dont have to generate every single HTML Element with their classes and src values with the appendChild-function and Dot-Notations in a for-loop?
Im thinking of something like:
for(let i = 0; i<=5;i++){
var element = new element(class,src1,src2 ...);
}
And the "element" is defined in a external class file or something familiar.
Im a beginner, so please show mercy :)
You'll need to clone the node from the template's content. For example:
const templateElement = document.querySelector("#someTemplate")
.content
.querySelector(".element");
// create an Array of nodes (so in memory)
const fiveNodes = [];
for (let i = 0; i < 5; i += 1) {
const nwNode = templateElement.cloneNode(true);
// ^ clone the whole tree
nwNode.querySelector("p.name").textContent += ` #${i + 1}`;
fiveNodes.push(nwNode);
}
// append the nodes to document.body
// this is faster than appending every element in the loop
fiveNodes.forEach(el => document.body.append(el));
<template id="someTemplate">
<div class="element">
<p class="name">I am node</p>
<div class="logo"></div>
</div>
</template>
I have a PHP function that generates hierarchical view of some blog posts according to their category, child category, grand child category and so on. It generates a string containing div tags with its data attributes. I want to convert those divs to html <ul><li> based on their value of attribute aria-level.
Actual output from php method
<div role="heading" aria-level="1">Test 1</div>
<div role="heading" aria-level="2">Test 1.1</div>
<div role="heading" aria-level="3">Test 1.1.1</div>
<div role="heading" aria-level="3">Test 1.1.2</div>
<div role="heading" aria-level="1">Test 2</div>
<div role="heading" aria-level="3">Test 2.1.1</div>
<div role="heading" aria-level="2">Test 2.2</div>
Desired Output using php/js/jquery/ any framework
Test 1Test 1.1Test 1.1.1Test 1.1.2Test 2Test 2.1.1Test 2.2
What I have achieved so far ?
function buildRec(nodes, elm, lv) {
var node;
// filter
do {
node = nodes.shift();
} while(node && !(/^h[123456]$/i.test(node.tagName)));
// process the next node
if(node) {
var ul, li, cnt;
var curLv = parseInt(node.tagName.substring(1));
if(curLv == lv) { // same level append an il
cnt = 0;
} else if(curLv < lv) { // walk up then append il
cnt = 0;
do {
elm = elm.parentNode.parentNode;
cnt--;
} while(cnt > (curLv - lv));
} else if(curLv > lv) { // create children then append il
cnt = 0;
do {
li = elm.lastChild;
if(li == null)
li = elm.appendChild(document.createElement("li"));
elm = li.appendChild(document.createElement("ul"));
cnt++;
} while(cnt < (curLv - lv));
}
li = elm.appendChild(document.createElement("li"));
// replace the next line with archor tags or whatever you want
li.innerHTML = node.innerHTML;
// recursive call
buildRec(nodes, elm, lv + cnt);
}
}
// example usage
var all = document.getElementById("content").getElementsByTagName("*");
var nodes = [];
for(var i = all.length; i--; nodes.unshift(all[i]));
var result = document.createElement("ul");
buildRec(nodes, result, 1);
document.getElementById("outp").appendChild(result);
<div id="outp">
</div>
<div id="content">
<h1>Test 1</h1>
<h2>Test 1.1</h2>
<h3>Test 1.1.1</h3>
<h3>Test 1.1.2</h3>
<h1>Test 2</h1>
<h3>Test 2.1.1</h3>
<h2>Test 2.2</h2>
<p></p>
</div>
Problem to be resolved ?
As you can see above it is using Heading tags to sort. But unfortunately my category hierarchy are not limited to only 6th level. It may grow. So I want a JS/Jquery/any framework to convert some tags to ul/li structure based on their attribute value. If any changes from Backend side is needed I can change those attributes/tags to any from PHP side. If it can be done from PHP side easily then some example code snippets is also welcome. Consider the above div tags as a single string input. :)
HTML source:
<span class="specLink">
<specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty>
</span>
<br />
<span class="specLink">
<specialty2><a title="Hand Surgery" href="link3.aspx">Hand Surgery</a></specialty2>
</span>
How can I create a JQuery script which runs during page load to displays the same list taking from the HTML Source listed above?
E.g.:
<div class="justPad">
<a title="Plastic Surgery" href="link2.aspx" class="defaultLinks">Plastic Surgery</a>
</div>
<div class="justPad">
<a title="Hand Surgery" href="link3.aspx" class="defaultLinks">Hand Surgery</a>
</div>
How I would like it to be:
var k = "";
$(".specLink").each(function() {
var aLink = $(".specLink").replace(<%-- Remove the <specialty#></specialty#> tags and only keep the anchor link --%>);
k += '<div class="justPad">'; //.. as many entries that shows up
k += aLink; //.. as many entries that shows up
k += '</div>'; //.. as many entries that shows up
});
//Once I have added
$(".addSpecialties").html(k);
Blank HTML:
<div class="serviceHolder brClear addSpecialties">
//add inside here from the JQuery above
</div>
Something like:
var specialties = $(".specLink a").map(function() {
return $('<div class="justPad">').append( $(this).clone() )[0];
}).toArray();
$(".addSpecialties").empty().append(specialties);
Hi I have the following recommendation from an expert and I am trying to rebuild my Code based on these recommendations:
from $.each() you can return true or false. If you return false, the
loop stops.
Try not to build HTML from concatenated strings. This is prone to XSS
vulnerabilities that are easy to avoid. jQuery gives you the tools to
build HTML safely.
Generally, for the same reason, try to avoid working with .html(),
especially if you already have DOM elements to work with.
Don't use inline event handlers like onclick. At all. Ever.
This is the new Code I am working on:
var page = 1;
$(document).on('click', '#devotionclick', function blogs() {
$('#postlist').empty();
// $('#category').prepend('<div class="categories_listing"><span data-type="blogs" data-category="5">Blog Category</span></div>');
var count = "5";
var result = $.getJSON('http://howtodeployit.com/api/get_posts/?count=' + count + '&page=' + page, function (data, status) {
if (data !== undefined && data.posts !== undefined) {
$.each(data.posts, function (i, item) {
var str = item.title;
$('#postlist').append('<div class="article"' + item.id + '"><div>' + item.title + '</div><div>' + item.excerpt + '</div></div>');
if (data !== undefined) {
$('#stats').text('Page ' + data.query.page + ' of ' + data.pages + ' | Total posts ' + data.count_total + '');
}
if (data.query.page < data.pages) {
$("#loadmore").show();
} else {
$("#loadmore").hide();
}
});
page++;
}
});
$('#postlist').append('<div id="loadmore"><div id="stats"></div><div id="loadmore">load more</div></div>');
$('#loadmore').click(blogs);
});
HTML:
!-- Page: home -->
<div id="home" data-role="page">
<div class="ui_home_bg" data-role="content"></div>
<div data-role="listview">
Daily Devotional Messages
</div><!-- links -->
</div><!-- page -->
<!-- Page: Daily Devotional Messages -->
<div id="devotion" data-role="page">
<div data-role="header" data-position="fixed">
<h2>Daily Devotional Messages</h2>
</div><!-- header -->
<div data-role="content" id="postlist"> </div><!-- content -->
</div><!-- page -->
The issues I am having right now is:
When I click on the Button it Loads the first 5 Posts but when I click on the 'load more' Text, it Loads the next 5 rather than Appending to existing Lists.
The Lists isn't displayed as a Listview item which should be clickable
Problem 1
It is because of $('#postlist').empty(); in the click handler.... you are removing all items from the page before loading new items. Remove this
I've a index.html page. Also this page contains lots of page like #home, #list #contacts etc.
in #list part i dynamically get data from my webpage and generate listview. I want that, when user click any of list item, redirect to #imageDetail page and pass image URL to page and show image
here is the #imageDetail page part
<div data-role="page" id="detailedIMAGE" data-theme="a">
<div data-role="header" data-theme="b" data-position="fixed">
<h1>Image Detail</h1>
</div>
<div data-role="content">
<img id="imageDetayURL" name="imageDetayURL" src="glyphish-icons/158-wrench-2.png"/>
<input type="text" disabled="disabled" id="brewername" name="brewername" />
</div>
</div>
</div>
And below code is my javascript code to get json data dynamically.
<script>
$('#last5').live("click", function() {
$.ajax({
url: "http://mysqlservice.com/getdata.json",
dataType: 'jsonp',
success: function(json_results){
$("#imageListDetay").html('');
console.log(json_results);
$('#imageListDetay').append('<ul data-role="listview" id="tweetul" data-theme="c"></ul>');
listItems = $('#imageListDetay').find('ul');
$.each(json_results.results, function(key) {
html = '<h3>'+json_results.results[key].screen_name+'</h3><span id="detailed_image">'+json_results.results[key].resim_url+'</span><img WIDTH=200 HEIGHT=100 src="http://mywebpage.org/upload/'+json_results.results[key].resim_url+'" /><p class="ui-li-bside"><img WIDTH=8 HEIGHT=13 src="images/07-map-marker.png"/> '+json_results.results[key].adres_data+'</p>';
listItems.append('<li><a name="imageDetayGoster" href="#detailedIMAGE">'+html+'</a></li>');
});
$('#imageListDetay ul').listview();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//error
}
});
})
$("#detailedIMAGE").live("pagebeforeshow", function (e, data) {
var brewername = $('#detailed_image',data.prevPage).text();
$('#brewername').val(brewername);
$('#imageDetayURL').attr('src', 'http://mobil.harmankaya.org/'+brewername);
alert(brewername);
});
</script>
The problem is after page change alert(brewername) fires. But list all image urls that listed in listview not my selected.
How can i fixed this issue
Thanks in advance.
jQM Docs:
http://jquerymobile.com/test/docs/pages/page-dynamic.html
This is just quoting the docs but if you read the page it should give you an idea on how to accomplish this.
The application uses links with urls that contain a hash that tells
the application what category items to display:
<h2>Select a Category Below:</h2>
<ul data-role="listview" data-inset="true">
<li>Animals</li>
<li>Colors</li>
<li>Vehicles</li>
</ul>
Well, this is my way and works very good.
HTML
<div data-role="page" id="myPage">
<div data-role="content" id="myContent">
<ul data-role="listview" data-inset="true/false/whatever" id="myList"></ul>
</div>
</div>
Javascript
$("#myPage").live("pageshow",function(event){
// get your id from LINK and parse it to a variable
var json_list_callback = getUrlVars()[id];
// verify the URL id
if (json_list_callback === '') {json_list_callback === ''} //or what value you want
// define your path to JSON file generated by the ID declared upper
var json_URL = 'http://your.path.to.json.file.php.json?id=' + json_list_callback;
// get the JSON data defined earlier and append to your LIST
$.getJSON(json_URL,function(data){
var entries = data;
//populate our list with our json data
$.each(entries,function(index,entry){
// i use dummy data here, you can have whatever you want in youre json
$("#myList").append(
'<li>' +
// remember that this "page.html?id=' + entry.json_id + '" will be the link where getUrlVars will get the id declared earlier in function
'<a href="page.html?id=' + entry.json_id + '">' + entry.json_title + '<\/a>' +
'<\/li>'
);
});
//must refresh listview for layout to render
$("#myList").listview("refresh");
});
});
//this function gets from URL the id, category, whatever you declare like this: getUrlVars()['id'] or getUrlVars()['category'] after last symbol of "?"
// you can define your own symbol with this function
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.lastIndexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
This works for me like a charm and i'm using it very often!
live event has been deprecated, use 'on',
exmple: $("#detailedIMAGE").on("pagebeforeshow", function (e, data){ // code });