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 });
Related
I have a problem changing items after searching.
I looked at similar threads but found no solution there :(
It looks like the first time the page loads well - the first time the entire Index.cshtml page is loaded which contains a collection of books in the selected category.
There is a search engine on the page - after searching for "manual" - ajax correctly replaces elements with those containing "manual" in the name.
Then when I enter something into the search engine a second time (for example "exercises") - the content of the page does not change any more.
I tried to debug and I see that new items are correctly downloaded from the database - the condition "if (Request.IsAjaxRequest ())" is true and the items are passed to partial view - there the "foreach" loop goes through them. Unfortunately, after _Partial, nothing happens.
I can't find a mistake - the strangest thing is that the first ajax call works fine - only the second (and subsequent) bad.
CatalogController.cs
public ActionResult Index(string categoryName = null, string searchQuery = null)
{
if (categoryName == null)
categoryName = (db.Categories.Find(1)).Name;
var category = db.Categories.Include("Books").Where(x => x.Name.ToLower() == categoryName).Single();
var books = category.Books.Where(x => (searchQuery == null || x.Title.ToLower().Contains(searchQuery.ToLower()) || x.SubTitle.ToLower().Contains(searchQuery.ToLower()) || x.Level.ToLower().Contains(searchQuery.ToLower())) && !x.Inaccessible);
if (Request.IsAjaxRequest())
return PartialView("_PartialBooksList", books);
else
return View(books);
}
Index.cshtml
<form class="o-search-form" id="search-form" method="get" data-ajax="true" data-ajax-target="#booksList">
<input class="o-search-input" id="search-filter" type="search" name="searchQuery" data-autocomplete-source="#Url.Action("SearchTips")" placeholder="Search" />
<input class="o-search-submit" type="submit" value="" />
</form>
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
#section Scripts
{
<script src="~/Scripts/jquery-3.5.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
var setupAutoComplete = function () {
var $input = $(this);
var options =
{
source: $input.attr("data-autocomplete-source"),
select: function (event, ui) {
$input = $(this);
$input.val(ui.item.label);
var $form = $input.parents("form:first");
$form.submit();
}
};
$input.autocomplete(options);
};
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-filter").each(setupAutoComplete);
$("#search-form").submit(ajaxSubmit);
});
</script>
}
_PartialBooksList
#model IEnumerable<ImpressDev.Models.Book>
#using ImpressDev.Infrastructure
<div class="row">
#foreach (var book in Model)
{
<div class="col-12 col-xl-4">
<a class="o-shop-link" href="#Url.Action("Details", "Catalog", new { bookId = book.BookId })">
<div class="o-shop-item">
<img class="o-shop-img" src="#Url.BookPhotoSourcePath(book.PhotoSource)" />
<div class="o-shop-text">
<h2>#book.Title</h2>
<h6>#book.SubTitle - #book.Level - <b>#book.Price zł.</b></h6>
+ Add to cart
</div>
</div>
</a>
</div>
}
</div>
Please help
I am not sure if this is the case, but try to change this code:
$($targetElement).replaceWith($newContent);
To this:
$($targetElement).html($newContent);
I think the problem is the div element with id="booksList" is replaced after first search. So you don't have this element in the second search.
I looked through the code step by step and found a solution to my problem.
In the first search, replace id="booksList"
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
partial view in which there was only without id = booksLists.
In the next search there was no ID in this place and there was nothing to replace.
I'm trying to sort a list of divs with the properties shown by particular attributes (gender, level, name etc) using the following script:
html:
<div id="sortThis" class="col-xs-12 alert-container">
<div id="1" class="container-element sortable box box-blue" data-gender="1" data-level="4" data-name="AAA"> <h3>AAA</h3><div class="panel-body">AAA is resp</div>
</div>
<div id="2" class="container-element sortable box box-pink" data-gender="2" data-level="3" data-name="DDD"><h3>DDD</h3><div class="panel-body">DDD is a s</div>
</div>
<div id="3" class="container-element sortable box box-blue" data-gender="1" data-level="2" data-name="FFF"><h3>FFF</h3><div class="panel-body">FFF has mad</div>
</div>
<div id="4" class="container-element sortable box box-pink" data-gender="2" data-level="4" data-name="CCC"><h3>CCC</h3><div class="panel-body">CCC has ma</div>
</div>
<div id="5" class="container-element sortable box box-pink" data-gender="2" data-level="2" data-name=EEE><h3>EEE</h3><div class="panel-body">EEE is a f</div>
</div>
<div id="6" class="container-element sortable box box-blue" data-gender="1" data-level="3" data-name="BBB"><h3>BBB</h3><div class="panel-body">BBB is an ou</div>
</div>
</div>
<button id="sLevel" class="LbtnSort">Sort by Level</button><br/>
<button id="sGender" class="GbtnSort">Sort by Gender</button><br/>
js:
var LdivList = $(".box");
LdivList.sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
var GdivList = $(".box");
GdivList.sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
/* sort on button click */
$("button.LbtnSort").click(function() {
$("#sortThis").html(LdivList);
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GdivList);
});
when the .sortable divs are static, the sort works fine, as this jfiddle shows, however if the contents of the #sortable div (i.e. .sortable divs) are dynamically generated (in this case as the result of a form submit), when the sort button is pressed, the entire contents of the #sortable div disappears, and I can't seem to get it to work.
Any help or suggestions would be appreciated.
edit: The code for dynamic generation of the list is as follows - effectively it's an AXAX form submit that pulls data from a sorted list of items and outputs them.
$('#formStep2').submit(function(event) {
// get the form data
var studentArray = [];
$(".listbox li").each(function() {
studentArray.push({
'name': ($(this).text()),
'gender': ($(this).closest('ol').attr('id')).substr(0, 1),
'level': ($(this).closest('ol').attr('id')).substr(2, 3),
'topic': ($('input[name=topic]').val())
})
});
var studentString = JSON.stringify(studentArray);
console.log(studentString);
var formData = {
'students': studentString,
};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'process_step2.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
// using the done promise callback
.done(function(data) {
if (!data.success) {
// error handling to go here.....
} else {
$('.alert-container').empty();
var obj = JSON.parse(data.message);
//sort the array alphabetically by name (default status)
var test = obj.sort(function(a,b){
var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
console.log(test);
var i=0;
test.forEach(function(st) {
console.log(st['name']);
var gen = (st['gender'] == 1) ? "blue" : (st['gender'] == 2) ? "pink" : NULL;
$('.alert-container').append('<div id="' + (i+1) + '" class="container-element sortable box box-' + gen + '" data-gender="' + st['gender'] + '" data-level="' + st['level'] + '" data-name="' + st['name'] + '"><h3>' + st['name'] + '</h3><div class="panel-body"><div class="col-xs-9"><i class="fa fa-quote-left fa-3x fa-pull-left fa-' + gen + '" aria-hidden=:true"></i>' + st['comment'] + '</div></div></div>');
i++;
});
// jump to the next tab
var $active = $('.wizard .nav-tabs li.active');
$active.next().removeClass('disabled');
nextTab($active);
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
You are defining LdivList and GdivList inline with your code so they are defined on DOM ready. You have to wrap the definition of those inside a function and call it on click:
$(document).ready(function(){
$("button.LbtnSort").click(function() {
$("#sortThis").html(GenerateLdivList);
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GenerateGdivList());
});
});
function GenerateLdivList(){
var LdivList = $(".box");
LdivList.sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
}
function GenerateGdivList(){
var GdivList = $(".box");
GdivList.sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
}
As #theduke said, the lists are probably empty at the time you sort them. Here's a simple change that will read and sort the lists when you click the buttons instead. (Not tested.)
var LdivList = function () {
return $(".box").sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
};
var GdivList = function () {
return $(".box").sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
};
/* sort on button click */
$("button.LbtnSort").click(function() {
$("#sortThis").html(LdivList());
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GdivList());
});
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
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.
So, I have observable array with sites, which is shown via template. If I'll add site to this array, template is not updated, but if I'll remove site from array – voila! template became updated and all previously added sites became displayed too.
If I'll use nifty hack (commented in code) with replacement of whole array to new one then everything works.
BTW, I load template via AJAX and use "ko.applyBindings(viewModel)" after. I assume that works fine, because initial sites are displayed correctly.
$(function(){
//site entry in user's sites list
var siteObject = function(url, lastChecked, status){
this.url = url;
this.lastChecked = (lastChecked == 'undefined') ? '' : lastChecked;
this.status = (status == 'undefined') ? 'not_checked_yet' : status;
this.toDelete = false;
this.remove = function() {viewModel.sites.remove(this)};
};
viewModel = {
//=========== sites list managment ==========================
sites: ko.observableArray(),
//on "add" click in "add site" form
addSite: function(){
var $form = $('#add_site_form');
var siteUrl = $form.find('input[name="site"]').val();
/*nifty hack <----
var sites = this.sites();
sites.push(new siteObject(siteUrl));
this.sites(sites);*/
this.sites.push(new siteObject(siteUrl));
},
//on "remove sites" button click
removeSites: function() {
var sitesToRemove = [];
$.each(this.sites(), function(){
if (this.toDelete) sitesToRemove.push(this);
});
if (sitesToRemove.length == 0)
alert("Ни одного сайта не было выбрано для удаления.");
else {
var message = "Вы точно хотите перестать отслеживать";
for (var i in sitesToRemove) {
message += "\n\"" + sitesToRemove[i].url + "\"";
}
message += "?";
if (confirm(message)) {
$.each(sitesToRemove, function(){this.remove()});
//save new sites list to db
this.saveSitesListToDb();
}
}
//hide form
$('#remove_sites_form').slideToggle();
//toggle checkboxes
$('#content_sites_list .site_info input[type="checkbox"]').slideToggle();
};
And the template:
<!-- end of menu -->
<div id="content_sites_list"
class="grid_12"
data-bind="template: {name: 'sites_list_template', foreach: sites}"></div>
<!-- Templates -->
<script id="sites_list_template" type="text/x-jquery-tmpl">
<div class="site">
<div class="site_panel grid_12">
<div class="site_info">
–
<input type="checkbox" value="${url}"
class="delete_checkbox" data-bind="checked: toDelete" />
${url.substr(7)}
{{if status == "200"}}
<img src="img/green_light.png" alt="ok"/>
{{/if}}
</div>
<div class="site_stat">
<div class="site_last_check">Последняя проверка: ${dateTimestamp}</div>
</div>
</div>
</div>
</script>
I've tried this on latest beta on knockoutjs and on stable one.
I have made a jsFiddle which works fine.
There were some problems that JSLint was complaining about in the removeSites function of the viewModel. I fixed those and added a button and input field to be able to give some input, and everything ran smooth.
So you could try updating your removeSites function and see if it helps you,