Get the id of elements dynamically created - javascript

I want to select the elements created dynamically using ajax by id, the code is:
$(function(){
$('#loadFeed').bind('click',function(){
$.getJSON('getData.php', function(json) {
var output="<ul id='feedsList'>";
for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
output+="<li class='post'>";
output+="<div class='text' id='"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";
output+="</li>";
}
output+="</ul>"
$(output).appendTo('.posts');
});
});
});
The html codes:
<div class="posts">
<!--dynamic content here-->
</div>
I tried to get the id using $(this).attr("id"):
$(".post").on("click",".text",function(){
var this_id =$(this).attr("id");
alert(this_id);
});
But it said undefined. How could I get the id correctly?Thanks!

$(".post") should be $('div.post'), because you're creating li from ajax request with same class. As div.post is existing in your DOM and you're appending you list to it.
That is,
$("div.post").on("click","li.post div.text",function(){
var this_id = this.id;
alert(this_id);
});

Numbers are not valid ids. Ids need to start with letters.
You will need to use something like this:
output+="<div class='text' id='post_"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";
Here'se the structure of a valid id: What are valid values for the id attribute in HTML?

Related

splitting up html returned from GET request on a certain class name

I am making a GET request which is returning two divs see below:
$.get('releases', function(data){
console.log(data);
}
data returns the following html
<div class="release">
<a href="link-1/">
<img src="image-1.jpg">
<h3>Test playlist 1</h3>
<p>This release is a playlist</p>
</a>
</div>
<div class="release">
<a href="link-1/">
<img src="image-1.jpg">
<h3>Test playlist 1</h3>
<p>This release is a playlist</p>
</a>
</div>
I am wondering how I can split the response up on the div with the classname release. The way I see it is that I would have each of the release divs and their contents in an array that I could then loop through and add responsive classes etc.
Instead of doing that, why not add the classes in the document ready function?
$(document).ready(function() {
$('div').find('.release').each(function(){
$(this).addClass( "myClass yourClass" );
});
});
Convert the data into a jquery Object and then use .find() to get the div's. Then loop through them to do what you need to do.
$.get('releases', function(data){
$(data).find('.release').each(function(i, el){
var $release = $(el);
$release.addClass('some-class');
});
}
I'm not sure what exactly what you were doing but this will loop through each div.
https://jsfiddle.net/ewsdnow6/
var data = '<div class="release"><img src="image-1.jpg"><h3>Test playlist 1</h3><p>This release is a playlist</p></div><div class="release"><img src="image-1.jpg"><h3>Test playlist 1</h3><p>This release is a playlist</p></div>';
var html = $.parseHTML(data);
$(html).each(function(){
console.log($(this));
});

Transmit javascript variable to a plugin function (async URL)

For My projet i need to know how i can transmit some variables to a async url. The plugin I use is a simple popover that call a URL to fetch html data and show the result.
I need to use $(this) because i have many URls with the same class. I must transmit the data-type (ex: picture) and the id of the product (data-id).
My link = Check this out
What i want to do (but it doesn't work) :
$('.product').webuiPopover({
var productType = $(this).data('type');
var id = $(this).data('id');
type:'async',
url:'/api/popover/'+ productType +'/'+id
});
Is it possible ? How i can do that ?
Note : here is the plugin I use (github : sandywalker/webui-popover)
You have to initialize webuiPopover for each .product element individually. Do something like this:
$('div').each(function(index, el){
$(el).webuiPopover({
title: $(el).data('foo') // Direct access to the data attributes of this element
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.webui-popover/1.2.5/jquery.webui-popover.min.js"></script>
<div data-foo="First title">Hello</div>
<div data-foo="Second title">Goodbye</div>
If you want to add variable then you can do it like:
$('.product').each(function(i,t){
var t = $(t);
t.webuiPopover({
type:'async',
url:'/api/popover/'+ t.data('type') +'/'+ t.data('id')
});
});

Filtering data in Javascript

I have a list of elements (DIVs) on my html page as below.
There is a list of hashtags on the same page.
I need that when the user clicks on the hashtag (e.g. #bacteria) only those DIVs that contain that hashtag are shown.
What would be the most lightweight and easy way to implement that?
<div class='entry'>
<p>#antibiotics destroy #e-coli and that's not good!!!!</p>
<!-- Hashtags: #antibiotics #eColi -->
<!-- UID: 755a2a60-972e-11e3-a464-872f2fc4dea2 -->
</div>
<div class='entry'>
<p>#bacteria can be #friendly, such as #e-coli for example</p>
<!-- Hashtags: #bacteria #friendly #eColi -->
<!-- UID: 6cc66d00-972e-11e3-a464-872f2fc4dea2 -->
</div>
<div class='entry'>
<p>#antibiotics can fight #bacteria</p>
<!-- Hashtags: #antibiotics #bacteria -->
<!-- UID: b37992c0-9686-11e3-8b2c-c97ae6645b3b -->
</div>
I know that Angular is powerful for this kind of stuff, but I'd like to use something lightweight and easy. Like maybe it's possible to do it with jQuery or something...
FYI the whole thing runs on Node.Js / Express.Js with EJS rendering.
Thank you!
UPDATE
Suppose now I have several hashtags I need to check for. Like as if contains variable is not a string but an array and i need to only show entries that contain ALL of this array's values. How would I change the code? Trying to do that, but can't manage... Thank you so much!
Use the :contains jquery selector
$(document).ready(function(){
$('.entry').hide();
$('.links').on('click','a',function(e){
var $ctx = $(e.target);
var contains = $ctx.text();
$('.entry').hide();
$('.entry:contains('+contains+')').show();
return false;
});
});
Sample : http://jsfiddle.net/LA3tD/
EDIT
you can use text with commas and then split, or use data attribute with some separator and split it afterwards for a concatenated filter selector
$(document).ready(function(){
$('.entry').hide();
$('.links').on('click','a',function(e){
var $ctx = $(e.target);
var contains = $ctx.text();
$('.entry').hide();
if(contains.indexOf(',')!=-1){
var tags = contains.split(',');
var filt = '';
$.each(tags,function(i,el){
filt += ':contains('+el+')';
});
// :contains can be concatenated multiple times f.e.: ":contains(foo):contains(bar)"
$('.entry'+filt).show();
}else{
$('.entry:contains('+contains+')').show();
};
return false;
});
});
Updated sample: http://jsfiddle.net/LA3tD/1/
Ideally, you'd incorporate your hash-tag data into the divs themselves...perhaps with the data-* attribute:
<div class='entry' data-hashtags='antibiotics bacteria'>
Then via jQuery you could loop through them hiding the ones that don't match:
var clickedHashtag = x //get the clicked on hashtag however you like
$('.entry').each(function(){
if($(this).data('hashtags').indexOf(clickedHashtag)>=0){
$(this).hide()
}
})
Fiddle: http://jsfiddle.net/Jz3gZ/
Untested:
$('.entry').each(function(item) { $(item).show($item.is('.' + hashtag)); });
You would have to add the hashtag as a class, of course:
<div class="entry antibiotics">

Jquery - $(this) id from selector group

So
I've defined a simple list and an output
<div class="item-list">
<p id="One">First Item</p>
<p id="Two">Second Item</p>
<p id="Three">Third Item</p>
</div>
<div class="box">Add Stuff in Here!</div>
And
I've written this script
$(".item-list > p").click(function(){
var thisId = (this.id);
$(".box").append('<p>' + thisId + '</p>');
});
I want
each item, on click, to append its id as text inside .box element
Like So
<div class="box>One</div>
And this works
just like you'd expect. JS Fiddle of the simplified Working Example.
But in my more complex example:
the id of the selected element
(this.id)
comes back as ...
Ew..
undefined.
Here's a JS Fiddle of the more complex version of this:
http://jsfiddle.net/pQz3W/4/
What's causing these id's to return undefined?
To be clear, In the more complex example, I'm doing the same thing, it's just crowded by other functionality. Something in there is causing my id to come back as undefined.
I'll keep posting updates to this fiddle as I clean the code up more and more to pertain only to what's necessary to be there for this question!
You have an array
ServiceArray = [
[
["SplashPage", "Splash Page", "hey!"],
["GamingWebsite", "Gaming Website", "yo!"],
["BasicWebsite", "Basic Website", "hi!"],
["AdvancedWebsite", "Advanced Website", "ooh!"],
["FlexWebsite", "Flex Website", "ahh!"],
......etc
and you have ID's that you're trying to look up in that array like this
var thisId = this.id;
var outputList = ServiceArray[0][thisId][2];
but there are no associative arrays in javascript, and the keys you're looking for doesn't exist. You need to rebuild that array with objects that has keys and values that actually match what you're looking for.
try this: var thisId = $(this).attr("id");

get id of first div in page loaded via ajax

I'm using $.get function for loading partial view:
$.get('/desk/nextstep', function (data) {
var ids = $(data).filter(':first').attr('id');
alert(ids);
});
I want to get id of first(root) div, but this code not works:
var ids = $(data).filter(':first').attr('id');
I get undefined alert message. How to solve it?
Thanks.
UPDATE:
In the data html code:
<div id="step1" class="scroll-pane">
<div class="scroll_cont">
//other content
</div>
</div>
Try this:
$.get('/desk/nextstep', function (data) {
var ids = $('<div/>').append(data).find(':first').attr('id');
alert(ids);
});
You can use native method match. ;)
var ids = data.match(/id="([^"]+)"/);
Preview - http://jsfiddle.net/fsGe6/

Categories