Get JSON appended items in another div - javascript

I am trying to get a JSON appended item to show on click in another div.
For example -
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
this gets my JSON information and adds it to .mydiv for each item.
Now - I am trying to get this information again, to show in another div, but only for the selected item. I have tried to add a click function to show the JSON information but only for the selected, but with no luck.
$('.mydiv').click(function() {
$(".seconddiv").append(field.name);
});
If anyone can put me on the right track it would be much appreciated.
Thanks!
EDIT
My HTML
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="mydiv">
<h1>...</h1>
</div>
</div>
<div class="col-md-4">
<div class="seconddiv">
<h1>...</h1>
</div>
</div>
</div>
</div>
EDIT 2
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
$(document).on('click', 'div.newdiv', function(){
$('div.seconddiv').append( $(this).html() );
});
});
EDIT 3:
So, This is working, BUT it is looping through each JSON and pulling the name through, I basically need only this name.
$(document).ready(function() {
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
$('.newdiv').click(function() {
$(".seconddiv").append(field.name); // HOW TO ONLY GET THIS FIELD NAME, NOT FOR EACH JSON ITEM
});
});
});

Functionality is a little unclear but here is a solution for when you want to display info and on click display only a selected name in a different div. I would recommend storing JSON attributes as data elements on newly created divs which can be later easily retrieved via a simple click handler.
jsfiddle here: https://jsfiddle.net/7961d87z/
And just the code
HTML
<!-- placeholder for your data -->
<div class="mydiv"></div>
<!-- placeholder for click events -->
<div class="result"></div>
Javascript
//fake data
result= [{name:"item1", event: "something"}, {name:"item2", event: "someevent"}];
$.each(result, function(i, field){
//create an element and append data attribute to the element - in this case field name
el = $("<div class='newdiv'>" + field.name + "," + field.event + "</div>").data("name", field.name);
//append element to DOM
$(".mydiv").append( el );
})
//define a click handler for all new elements to display data in a div
$(".mydiv").on( "click", ".newdiv", function() {
$(".result").text( $( this ).data("name") );
});

It isn't in your DOM element on load as you append it. What you want to do is actually manage the clicked element:
jQuery(document).on('click', 'div.mydiv', function(){
});
You must also remember, that you can't access the JSON outside of your $.getJSON() call.
Edit
To only show your clicked one, you'll need to fetch the .html() and append that to the new div. That looks something like this:
jQuery(document).on('click', 'div.mydiv', function(){
jQuery('div.mynewdiv').append( jQuery(this).html() );
});

This creates HTML for element having class mydiv
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
Use this to append to .seconddiv the information you want
$(document).on('click','.newdiv',function() {
$(".seconddiv").append($(this).html()); // fieldName,fieldEvent
});

Related

jquery call function from dynamic div

I am using jquery. I have a div that is populated by jquery. Inside div, there is a list of items under row tag. And, Inside, the dynamic div section, I also have a anchor tag. On clicking on that anchor tag, I want to call the ajax function. Is it even possible?
var content='';
$.each(products, function(key, value) {
content += '<div class="row">' +
'<img src="' + value.image + '" class="img img-responsive" style="height: 65px;"/>' +
'<h3>' + value.name + '</h3>' +
'<p>' + value.category + '</p>' +
'</div>' +
'Delete' +
'<hr>';
});
modal.find('.modal_product_list').html(content);
When the anchor tag is clicked, I want to call ajax function. Here is my ajax sample:
$('.delete_product_from_space').on('click', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});
The on click event is never fired. Is it possible to call like this? Or I am approaching in a wrong way?
You may try to add the event on modal, as the dynamically generated elements would not be available at the time of code execution. Try the below code,
$('.modal_product_list').on('click', '.delete_product_from_space', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});

How to add <div></div> and name+size+delete appear in new div. javascript jquery

I have used ajaxSubmit to upload file to linux server successfully. After upload file, name+size+delete should be appear in my website.
For example, 1.jpg、2.jpg、3.jpg were uploaded to server, my submit website shoule be appeared like:
1.jpg 3k delete
2.jpg 4k delete
3.jpg 5k delete
Before upload files, My html structure is :
<td style="width:30%" id="impPic">
<div class="btn">
<span>addFile</span>
<input id="fileupload" type="file" name="mypic">
</div>
<div class="files"><b>...</b><span>...</span></div>
</td>
After uploaded three files, I wanted html like:
<td style="width:30%" id="impPic">
<div class="btn">
<span>addFile</span>
<input id="fileupload" type="file" name="mypic">
</div>
<div class="files"><b>...</b><span>...</span></div>
<div class="files"><b>...</b><span>...</span></div>
<div class="files"><b>...</b><span>...</span></div>
</td>
My files has fixed css style:
.files{height:10px; font-size:10px;line-height:22px; margin:10px 0}
Here is my ajaxSubmit code:
var divD=1;
$(function () {
var files = $(".files");
newDiv = "<div class='files'+divD+''><b class='dataname'>'+data.name+'('+data.size+'k)</b> <span class='delimg' name='+data.name+'('+data.size+'k)' rel='+data.pic+'>delete</span></div>";
$("#fileupload").change(function(){
$("#myupload").ajaxSubmit({
dataType: 'json',
beforeSend: function() {
......
},
uploadProgress: function() {
},
success: function(data) {
$(newDiv).insertAfter($('#impPic div:eq('+divD+')'));
divD = divD + 1;
$('.files').html("<b class='dataname' >"+data.name+"("+data.size+"k)</b> <span class='delimg' rel='"+data.pic+"'>delete</span>");
},
error:function(xhr){
......
}
});
});
});
But unfortunately, it failed. I suppose files'+divD+'.html is wrong. Who can help me ?
I see two problem with your code...
First was the html string "newDiv" that you are trying to insert and the second is the invocation for jQuery .html() on an string literal object "files'+divD+'".
You are expecting the newDiv object to have a concatenated html string with the value of divD and the data came from the response but object data is undefined until the logic flows in the success callback.
and I believe the second problem would return a jquery TypeError problem, as you are trying to call the .html() function on a non DOM - jQuery object .
Update your code and try it this way:
newDiv = "";
...
success: function(data) {
newDiv = "<div class='files" + divD + "'><b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' name='" + data.name + data.size + "k' rel='" + data.pic + "'>delete</span></div>";
$(newDiv).insertAfter($('#impPic div:eq(' + divD + ')'));
divD = divD + 1;
$(".files" + divD).html("<b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' rel='" + data.pic + "'>delete</span>");
},
...
EDIT:
You can update the html string and add an Id to have a unique selector on each of the element with files class and instead of the above selector, change the class selector "." to an Id selector "#".
and your code will look like these...
newDiv = "<div id='files" + divD + "'class='files'"...
...
$("#files" + divD).html("<b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' rel='" + data.pic + "'>delete</span>");
If that doesn't suit your needs you can just leave the first example above and update your css selector to:
[class^='files'] instead of `.files`.
This will select all of the element with a class that begins with "files".
files'+divD+' is a string, and you try to call method html from string, which does not exist.
Try $('.files' + divD).html('something'); or files.find('.files' + divD).html('something');

Using jQuery with reddit API, trying to create seperate divs for each post

the problem is, it posts all the titles, then the urls, then the permalinks separately. I need the title link and etc for each post together.
here is my code:
$(document).ready(function() {
$.getJSON(
"http://www.reddit.com/r/pics.json?jsonp=?",
function foo(data) {
$.each(
data.data.children.slice(0, 10),
function(i, post) {
$("#reddit-title").append('<br>' + '<div class="post-title">' + post.data.title + '</div>');
$("#reddit-url").append('<br>' + '<div class="post-url">' + post.data.url + '</div>');
$("#reddit-permalink").append('<br>' + '<div class="post-permalink">' + post.data.permalink + '</div>');
$("#reddit-ups").append('<br>' + '<div class="post-ups">' + post.data.ups + '</div>');
$("#reddit-downs").append('<br>' + '<div class="post-downs">' + post.data.downs + '</div>');
$("#reddit-hr").append('<hr>');
}
)
}
)
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
here is what is outputs:
/r/pics has reached 9 million subscribers, becoming the third subreddit to do so and the first image based sub beginning with P to reach that milestone
TRON Mustang
His claw is actually stuck in the screen, but he's trying to play it cool
When Life Truly Comes Into View
I think I found Stargate
A very happy baby orca breaches the surface
Aurora over Finland
A couple years, thousands of sticky notes, thousands of playing cards, thousands of flash cards, and many many pieces of paper later.
The trunk of a rainbow eucalyptus (not photoshopped)
This guy's mushroom hunt was a success
http://www.reddit.com/r/pics/comments/3edbsk/rpics_has_reached_9_million_subscribers_becoming/
//i.imgur.com/j2XIS80.jp
://i.imgur.com/oDORUZk.jp
//i.imgur.com/Zm7KJvd.jp
/i.imgur.com/0TnK4YJ.jp (had to make these not valid links for posting purposes)
://i.imgur.com/NhRGsb8.jp
://i.imgur.com/JYWOtEd.jp
h//imgur.com/a/nAMQ
://i.imgur.com/JhFz2AL.jp
//imgur.com/C0kpFx
/r/pics/comments/3edbsk/rpics_has_reached_9_million_subscribers_becoming/
/r/pics/comments/3eco7r/tron_mustang/
/r/pics/comments/3ebyag/his_claw_is_actually_stuck_in_the_screen_but_hes/
/r/pics/comments/3ebfdh/when_life_truly_comes_into_view/
/r/pics/comments/3ebq5b/i_think_i_found_stargate/
/r/pics/comments/3eb4gi/a_very_happy_baby_orca_breaches_the_surface/
/r/pics/comments/3eb121/aurora_over_finland/
/r/pics/comments/3ebzcu/a_couple_years_thousands_of_sticky_notes/
/r/pics/comments/3ec758/the_trunk_of_a_rainbow_eucalyptus_not_photoshopped/
/r/pics/comments/3ec03u/this_guys_mushroom_hunt_was_a_success/
8
4501
5471
5301
3847
5449
4904
1409
1125
1185
0
0
0
0
0
0
0
0
0
0
You're calling the element to append to with the id tag. So what happens is that each time you cycle through, you re-call the same id tag rather than a new grouping. For example:
If your page looks along the lines of this:
<div id="reddit-title">
</div>
<div id="reddit-content">
</div>
For each cycle, your code will pick out the title div for each title, and content div for each snippet and then append:
<div id="reddit-title">
<div>Title 1</div>
<div>Title 2</div>
</div>
<div id="reddit-content">
<div>Content 1</div>
<div>Content 2</div>
</div>
As suggested by some of the other answers, create a new div group at the beginning and append each item to that new div, rather than individually calling elements to append your new data.
I think you'll need to add a new element which contains a title, URL, permalink, etc. for each item. Right now it sounds like you have just one element for each field but you really need one per item field.
Also, the ids should be changed to classes since there will be multiple elements with the same I'd otherwise. Then your selectors would be like this '.reddit-title' instead of '#reddit-title'
You could create a container div and then append the items to it, much like you have, and then append to a parent element like:
function(i, post) {
$container = $("<div class='reddit-post'>")
$container.append('<br>' + '<div class="post-title">' + post.data.title + '</div>');
$container.append('<br>' + '<div class="post-url">' + post.data.url + '</div>');
$container.append('<br>' + '<div class="post-permalink">' + post.data.permalink + '</div>');
$container.append('<br>' + '<div class="post-ups">' + post.data.ups + '</div>');
$container.append('<br>' + '<div class="post-downs">' + post.data.downs + '</div>');
$container.append('<hr>');
$('body').append($container)
}

jquery on click event doesn't work when using ajax

I am doing an ajax to pull information from a spreadsheet on my google drive, and then using the following code to display them in HTML:
I have this HTML:
<section class="p-booking" id="booking">
<div class="container">
<div class="row">
<div class="event-box">
<!-- caixas puxados do drive -->
</div>
</div>
</section>
And this JS:
$.getJSON(url, function (data) {
var caixasEvento = [];
caixasEvento.push('<div class="col-md-3">');
caixasEvento.push('<div data-id="' + something + '" class="box">');
caixasEvento.push('<h1 class="day">' + something + '</h1>');
caixasEvento.push('<h1 class="local">' + something + '</h1>');
caixasEvento.push('<img class="local-img" src="' + image + '">');
caixasEvento.push('</div>');
caixasEvento.push('</div>');
$('.event-box').append(caixasEvento.join(''));
});
And then I need an alert every time someone clicks the box:
$('.box').on('click', function() {
alert('test')
});
I'm using a script link tag in the bottom of my html document.
the box is normally appearing with all the drive information.
It does not work. I believe that is a problem related to the ajax, because if I create a div with the 'box' class, the alert works.
I'm guessing this is happening because the box element doesn't exist on the page when you try to setup the listener. Try this:
$('.event-box').on('click', '.box', function() {
// do stuff here
});
Try this:
$('.box').each(function()
{
$(this).click(clickHandler);
});
function clickhandler()
{
alert('test')
}

How do i make jQuery unique ID for div for click event?

I need on selection to append div element to the another div, I have done it, and also every time when I select new selection, it should append new div.
the problem is, those appended div's have same id, so I can not delete particular element. I have made them unique with declaring var and combining id with a string, like : id="add_marke'+selectedKey+'" BUT I cant do something like this jQuery( "#add_marke'+selectedKey+'" ).click(function() {
How can I select ID when I make unique ID?
var selectedKey = jQuery("#model").val();
jQuery('#example').append('' + '<div class="add_marke" id="add_marke' +
selectedKey + '" >' +
' <div class="car_tag"><span class="lbl"><span id="car_name" class="icon-remove"></span></div> ' +
'&nbsp' +
' <select name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>' +
'&nbsp' + '</div>');
jQuery("#car_name").click(function() {
jQuery("#add_marke\\.selectedKey").remove();
});
You can add the IDs as you do with a predefined prefix:
... id="add_marke_' + selectedKey + '" ...
And then bind the click with a jQuery selector for all elements that have the ID starting with add_marke_:
$('div[id^="add_marke_"]').click()
What you need to do is add the click handler to the class name shared by all of these divs. Once the click handler has been triggered, you can then extract the relevant id of the element and compose a selector from that id.
jQuery( ".class_name" ).click(function() {
var id = jQuery( this ).attr( "id" );
jQuery( "#" + id ).remove();
});
You can use
jQuery( ".icon-remove" ).click(function() {
jQuery(this).parent().parent().parent().remove();
});
Since an ID must be unique you have one of two options, as I see it:
Appending some sort of counter or numeric identifier to the ID, so you always have a unique ID (e.g., count the number of elements and then attribute your ID as my-id-1, my-id-2, etc.) Here you would have to write the DOM query in such a way that searches only for those IDs which begin with a given pattern, div[id^="my-id-"]
Use a class to identify the object in terms of any interactions you would like to provide for all of these <div> elements which have the same structure. Here, you can query based on a common class, in your case .add_marke.
<div class="parentElement">
<span>jagadeesh</span>
<span class="icon-remove car-remove"></span>
<button >Remove</button>
</div>
$('.car-remove').on('click',function(){
var mainElement = $(this).closest('.parentElement')
/// do what ever you want with main element. it selects only current parent
//element
mainElement.remove();
})
Did you want to do something like this?
http://jsfiddle.net/Wg9FE/1/
var selectedKey = "someId";
jQuery('#example').append('' +
'<div class="add_marke" id="add_marke'+selectedKey+'" >' +
' <div class="car_tag"><span class="lbl"><div id="car_name" class="icon-remove"></div></div> ' + '&nbsp' +
' <select name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>'+ '&nbsp' +
'</div>');
jQuery( "#car_name" ).click(function() {
jQuery( "#add_marke" + selectedKey ).remove();
});

Categories