click on dynamically generated elements not working jquery [duplicate] - javascript

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 8 years ago.
i found some Answers on this question like in this link but it not working for me i don't know if i do some thing else wrong i'm trying to create some html when the page load then click on html element that has been create dynamically but the click event on the specific element don't work here is my code :
$(function () {
console.log("Category Page Script loaded");
$.post('/Category/GetCategories', {}).success(function (data) {
console.log(data);
$Category = $('ul#Category-filter');
$Category.empty();
console.log("coustom empty");
var html = '';
for (sub in data) {
console.log(data[sub].CategoryID, data[sub].CategoryName);
var html = '<li class="dropdown-tree CategorySelected">'
+ '<a class="dropdown-tree-a" data-id="' + data[sub].CategoryID + '">' + data[sub].CategoryName + ' COLLECTION </a>'
+ '<ul class="category-level-2 dropdown-menu-tree" id="' + data[sub].CategoryID + '">'
+ '</ul>'
+ '</li>'
console.log(html);
$Category.append(html);
}
}).error(function () {
console.log('error');
});
//___________________________________________________________________________
$('li.CategorySelected').on('click', function () {
console.log("clickd");
// Get the id from the link
var SelectedCategoryID = $(this).attr("data-id");
$CategorySelected = $('ul#' + SelectedCategoryID);
$CategorySelected.empty();
console.log("CategorySelected empty");
var html = '';
if (SelectedCategoryID != '') {
$.post("/SubCategory/GetSubCategories", { SelectedCategoryID: SelectedCategoryID },
function (data) {
console.log(data);
for (sub in data) {
console.log(data[sub].SubCategoryID, data[sub].SubCategoryName);
var html = '<li>' + data[sub].SubCategoryName + ' </li>'
console.log(html);
$CategorySelected.append(html);
}
});
}
});
//_________________________________________________________
});

$('ul#Category-filter').on('click', 'li.CategorySelected', function(){
//your scripts here
});

Related

How do i retrieve data from a protected API via Jquery

this is my first time here so i hope i don't break any rules.
I have a Jquery code that retrieves info from an API that is written from a .net controller. Retrieving the infomration from the API works well, but now that i have to make the user sign in to view the API(Json), it of course stopped working in jquery. Is there anyway i can let the Jquery code "sign in" so it can retrieve data from that API while it's protected with password (authorize)?
Thanks
UPDATE
here is the Jquery Code
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('url/here', function (data) {
console.log(data);
var items = data.map(function (item) {
return item.id + ': ' + item.firstName + ': ' + item.lastName;
});
showData.empty();
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
});
});

Why is my json get request not working?

I am working on building a movie search app. It is my first time using json. I cannot figure out why my code is not working. I have it running on localhost using xampp.
On submit
$('.search-form').submit(function (evt) {
// body...
evt.preventDefault();
var $searchBar = $('#search');
var omdbApi = 'http://www.omdbapi.com/?';
var movieSearchTerm = $searchBar.val();
var searchData = {
s:movieSearchTerm,
r:json
}
Here is the callback function
function displayMovies(data) {
// for each search result
$.each(data.items,function(i,movie) {
movieHTML += '<li class="desc">';
//movie title
movieHTML += '<a href="' + movie.Title + '" class="movie-title">';
//release year
movieHTML += '<a href="' + movie.Year + '" class="movie-year">';
//poster
movieHTML += '<img src="' + movie.Poster + '" class="movie-poster"></li>';
$('#movies').html(movieHTML);
}); // end each
// movieHTML += '</li>';
}
$.getJSON(omdbApi, searchData, displayMovies);
});//end submit
r:json
You made a typo.
You haven't created a variable called json and the service expects the value of r to be json.
String literals need to be surrounded with a pair of " or '.
data.items
And the JSON returned doesn't have items, it has Search.

Function within function in JavaScript - Need to understand this code:

I have below code within a function called render. How do I call the str variable value outside render function?
Also, please can you explain below code? I'm fairly new to js and head is hurting looking at the function calls having functions as a parameter.
My understanding is that app.getList is an object which takes function as a parameter? but it is not returning anything. Sorry, I'm lost here.
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
Full Code:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});
app.getList is probably asynchronous (meaning it runs in the background). The function you've passed to it is a callback. That function will be ran at some point in the future, once the AJAX call (or whatever asynchronous method is ran) is done.
Your callback is passed reply, which is the "return" value from getList(). You cannot access str from outside of this function. You need to do whatever code with reply and/or str in that function only.

dynamically generated elements not displaying on the screen

I create some dynamically generated html by jQuery and then add some click event on this generated html.
The click event work fine and the code inside run correctly and add some anther dynamically generated html to the first dynamically generated html on the page.
So what I am trying to do is first dynamically generated html then add click event on it after the click event is triggered, add some more dynamically generated html to the fist dynamically generated html.
This all works fine but the second dynamically generated html not displaying on the screen, I inspect element on the target html and the html was generated but still not displayed on the screen.
Here is my code :
$(function () {
console.log("Category Page Script loaded");
$.post('/Category/GetCategories', {}).success(function (data) {
console.log(data);
$Category = $('ul#Category-filter');
$Category.empty();
console.log("coustom empty");
var html = '';
for (sub in data) {
console.log(data[sub].CategoryID, data[sub].CategoryName);
var html = '<li class="dropdown-tree CategorySelected" data-id="' + data[sub].CategoryID + '">'
+ '<a class="dropdown-tree-a">' + data[sub].CategoryName + ' COLLECTION </a>'
+ '<ul class="category-level-2 dropdown-menu-tree" id="category">'
+ '</ul>'
+ '</li>'
console.log(html);
$Category.append(html);
}
}).error(function () {
console.log('error');
});
//___________________________________________________________________________
$(document).on('click', 'li.CategorySelected', function () {
console.log("clickd");
// Get the id from the link
var SelectedCategoryID = $(this).attr("data-id");
console.log(SelectedCategoryID);
if (SelectedCategoryID != '') {
console.log('1');
$CategorySelected = $('#category');
console.log($CategorySelected);
console.log('2');
$CategorySelected.empty();
console.log('3');
console.log("CategorySelected empty");
console.log('4');
var html = '';
console.log('5');
$.post("/SubCategory/GetSubCategories", { SelectedCategoryID: SelectedCategoryID },
function (data) {
console.log(data);
console.log('6');
for (sub in data) {
console.log(data[sub].SubCategoryID, data[sub].SubCategoryName);
var html = '<li>' + data[sub].SubCategoryName + ' </li>'
console.log(html);
$CategorySelected.append(html);
console.log($CategorySelected);
}
});
}
});
//_________________________________________________________
});
This problem occurs only when parent element id is duplicate, please ensure that no dulipcate id is used for parent element.

'no image' icon while outputting AJAX-delivered content [duplicate]

This question already has answers here:
How to show Page Loading div until the page has finished loading?
(13 answers)
Closed 8 years ago.
I use AJAX requests to retrieve data from mySQL (link), after that I build a sequence of post. Every post has a feature image. So while in process of outputting the posts, the visitor sees 'no image' sign:
.
This lasts for a bit of second, but looks bad.
How can I prevent this sign from showing, or subtitute with a loading spin?
jQuery part for outputting the results
function postsBuilder(posts){
var contents ='';
$.each(posts, function(k, field){
if(field.link[field.link.length-1] == '/') {field.link = field.link.slice(0, field.link.length-1)};
contents += '<div class="post-container">';
//here I output the feature image
contents += "<div class='col_1'><div class='post_image'><img src='/images/icons/id_" + field.id + ".png'></div></div>";
contents += "<div class='col_2'><div class='post_name'><a class='post_name_link' target='blank' href=http://" + field.link + ">" + field.name + "</a></div>";
contents += "<div class='post_link'>" + field.link + "</div>";
contents += "<div class='post_content'>Content: " + field.content + "</div>";
if ( field.video.indexOf('you') >-1 ) {contents += "<div class='post_video'><a data-toggle='lightbox' href=" + field.video + ">Video</a></div>";}
contents += "</div></div><br />";
});
return contents;
}
One of examples when the function is called
$.ajax({cache:false,
url:str,
beforeSend: function() { $('#loadingDiv').show(); },
complete: function() { $('#loadingDiv').hide(); },
dataType :'json'})
.done(function(result){
var i, j, m=0;
var div_content="";
div_content += "<div><b>Category: ".concat(result[0].category).concat("</b></div>");
posts_array = [];
for (i=0,j=result.length; i<j; i+=size) { // slice whole JSON result into portions of at maximum 'size' posts in each
posts_array.push(result.slice(i, i+size));
m++;
}
div_content += postsBuilder(posts_array[0]);
...
$("#content").html(div_content);
});
Use the error event for images:
$(document).on('error', 'img', function () {
$(this).hide();
// or $(this).css({visibility:"hidden"});
});
Check out How to silently hide "Image not found" icon when src source image is not found

Categories

Resources