JSON append every four values to an element (each and iterations) - javascript

I'm currently appending the data from a JSON file to an element on my site, but I need it to work in iterations of every four. So, for each element it appends, it grabs four values, then the next four and so on.
This is what I have so far:
$.getJSON('works/api', function(r) {
var x = 0;
$.each(r.data, function(i, work) {
x++;
$('.each-works-caption ul').each(function() {
$(this).append('<li>'+ x + '. ' + work.title + '<br/><span>' + work.description + '</span></li>');
});
});
});
Which outputs ALL the work.title and work.description values for each JSON data, on every .each-works-caption ul but I need it to work in fours so on the first .each-works-caption ul it appends the first four values (or rows) and then on the second .each-works-caption ul it appends the second four values (or rows) and so on.
Hope this makes sense and I realise it's a little specific so I apologise in advance.
-R

$.getJSON('works/api', function(r) {
$.each(r.data, function(i, work) {
$('.each-works-caption ul:eq('+Math.floor(i/4)+')').append(
$('<li />', {html: i + '. ' + work.title + '<br/>'}).append(
$('<span />', {text: work.description})
)
)
});
});
FIDDLE

Related

Linked "Combos" not working correctly

Fiddle: https://jsfiddle.net/Mrbaseball34/kuj2cz5g/
In the code, I call GetYears to fill a <ul> with data. When a year is clicked on, it is supposed to append the selected year to the text of the flyout then load the makes <ul>
But, what is happening is it is "looping" through the years and calling yearClick for each year in the list after the that is clicked. Yes, it fills the makes <ul> but then begins looping yearClick() again.
Can anyone help out here? I can't see the forest for the trees, I guess...;-)
var year;
var make;
var model;
var ic;
GetYears();
$("#year-flyout").css("top", $(".m-assisted-decode").position().top);
$("#make-flyout").css("top", $(".m-assisted-decode").position().top + 40).hide();
$("#model-flyout").css("top", $(".m-assisted-decode").position().top + 75).hide();
$("#parts-flyout").css("top", $(".m-assisted-decode").position().top + 112).hide();
function GetYears() {
var data =
[{"year":"2017"},{"year":"2016"},{"year":"2015"},{"year":"2014"},{"year":"2013"},{"year":"2012"},{"year":"2011"},{"year":"2010"},{"year":"2009"}];
$.each(data, function(i, item) {
$("#years").append("<li class=\"year\">" + item.year + "</li>");
$(".year").on("click", yearClick);
});
$("#fa_year").hide();
$("#year-flyout").show();
}
function yearClick(event) {
year = $(this).text();
$("#year_value").attr("placeholder", $("#year_value").attr("placeholder") + ":" + year);
$("#year-flyout").hide();
// Get the Makes and populate the Makes Flyout
GetMakes();
}
function GetMakes() {
var data =
[{"make":"ACURA"},{"make":"AUDI"},{"make":"BMW"},{"make":"BUICK"},{"make":"CADILLAC"},{"make":"CHEVROLET"},{"make":"CHRYSLER"},{"make":"DODGE"},{"make":"FORD"},{"make":"GMC"},{"make":"HONDA"},{"make":"HUMMER"},{"make":"HYUNDAI"},{"make":"INFINITI"},{"make":"JAGUAR"},{"make":"JEEP"},{"make":"KIA"},{"make":"LAND ROVER"},{"make":"LEXUS"},{"make":"LINCOLN"},{"make":"MAZDA"},{"make":"MERCEDES-BENZ"},{"make":"MERCURY"},{"make":"MINI"},{"make":"NISSAN\/DATSUN"},{"make":"PONTIAC"},{"make":"PORSCHE"},{"make":"RAM"},{"make":"SAAB"},{"make":"SATURN"},{"make":"SCION"},{"make":"SMART"},{"make":"SUBARU"},{"make":"SUZUKI"},{"make":"TOYOTA"},{"make":"VOLKSWAGEN"},{"make":"VOLVO"}];
$.each(data, function(i, item) {
$("#makes").append("<li class=\"make\">" + item.make + "</li>");
$(".make").on("click", makeClick);
});
$("#make-flyout").show();
}
function makeClick(event) {
make = $(this).text();
$("#make_value").attr("placeholder", $("#make_value").attr("placeholder") + ":" + make);
$("#make-flyout").hide();
// Get the Models and populate the Models Flyout
// GetModels();
}
There's no need to attach the event listener after each added <li> since you're using the class. Just move it out of the each loop
$.each(data, function(i, item) {
$("#years").append("<li class=\"year\">" + item.year + "</li>");
});
$(".year").on("click", yearClick);
If you inspect your year element in Chrome inspector, you can see all the attached events on click, and see that it was firing the same event several times.

Unable to remove tr in a table using jquery

so I am having a problem in removing a particular tr in table using jquery.
So this is the scenario:
I have a table in which rows where clickable. And when I clicked one of them, I will be able to update the object data associated with that row. However, after updating the object, I want to reflect the changes in the td's of that particular tr.
My solution is, to remove the old tr and replace with the new tr. However, It did not remove the old tr instead just inserted the new tr. So this is my code:
function update_table_after_updating(selected_violator){
violators_table.find('tr').each(function (i, el) {
var tr = ($(this));
var td_text = $(this).find('td:first').text();
if(td_text == selected_violator.violator_id){
console.log(tr);
//I cant remove this row
tr.remove();
return false;
}
});
update_table(selected_violator);
}
The update_table() function
function update_table(violator){
var img_str1 = '<img class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.front_temp_file_path + '\">';
var img_str2 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.rear_temp_file_path + '\">';
var img_str3 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.right_temp_file_path + '\">';
var img_str4 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.left_temp_file_path + '\">';
violators_table.dataTable().fnAddData([
violator.violator_id,
violator.get_full_name(),
'Under Construction',
img_str1 + img_str2 + img_str3 + img_str4,
]);
$('#violators_tbl tbody tr').on('click', function(){
var td = $(this).find('td:first').text();
//returns violator object
selected_violator = get_violator(td);
show_modal('view_violator');
});
}
Thank you very much! Your responses will be greatly appreciated.
PS: I am using jquery DataTables.
Well this is kinda disappointing, I have searched through Jquery Docs then I have find this:
.empty() -> This method removes not only child (and other descendant)
elements, but also any text within the set of matched elements. This
is because, according to the DOM specification, any string of text
within an element is considered a child node of that element. Consider
the following HTML:
Unlike remove(). empty() also removes child nodes of the selected element.
And, voila! The tr has been removed.

How to pass the id of Div as an argument to a function

I have a Div that is dynamically added to a page with the click of a button using jQuery.
I would like to be able to remove the Div with the click of the cross-button.png using the RemoveArtist() function.
$("<div class=\"input-append\" id=\"artist"
+ artists.length - 1 + "\" ><label style=\"background-color:#e0ffff\">"
+ artistVal + "</label><img onclick=\"RemoveArtist()\" id=\"removeartist\""
+ " src=\"/Content/bootstrap/img/cross-button.png\" /></div>")
.appendTo(addDiv);
The remove artist fucntion should look like this:
var RemoveArtist = function (div,artistlength) {
$('div').remove();
artists.splice(artistlength, 1);
};
How can I pass the actual div to the RemoveArtist function and also the artistlength which is the artists.length - 1 value from the Div?
So basically I am trying to delete the Div and remove the artist from the artists array.
In my opinion, you'd be better of if you created actual elements instead of a string.
It's more stuff to write, but makes everyhing a lot easier to keep track of :
var input_append = $('<div />', {id: 'artist' + (artists.length - 1)}),
label = $('<label />', {style: 'background-color:#e0ffff',
text : artistVal
}
),
image = $('<img />', {id: 'removeartist',
src: '/Content/bootstrap/img/cross-button.png',
on: {
click: function() {
input_append.remove();
artists.splice(artists.length - 1, 1);
}
}
}
);
addDiv.append( input_append.append(label, img) );

JS or Jquery create unique span ID

I'm creating a li item with a span inside. I've built an onclick function in the span to grab the parent li's ID to pass into a JSON get request. I'm unsure of how to create a unique ID and read it in the JS function. Since this is built dynamically I didn't build a switch but I feel like i'm missing another option.
The problem here is that I can't capture the Li ID. I've tried this and also tried based on class, but all seem to be failing.
Li object creation:
$("#jdLists").append('<li class="bigger" id = "' + item.ID + '">'+
item.GROUP_NAME +
'<span title="Remove from list" class=" Sp icon icon-color icon-plus" style="float: right; vertical-align: middle;" '+
'onclick="spAdd()"></span>' +
'</li>');
on click function:
function spAdd() {
$(this).closest("li").attr('id');
}
Try like this:
// Should work for most cases
function uniqId() {
return Math.round(new Date().getTime() + (Math.random() * 100));
}
// Create elements properly and attach click event
// before appending to DOM so it delegates the event
var $li = $('<li/>', {
'class': 'bigger',
id: uniqId()
});
var $span = $('<span/>', {
'class': 'Sp icon icon-color icon-plus',
title: 'Remove from list',
text: 'I\'m a span',
click: function() {
alert( $(this).parent().attr('id') );
}
});
$('#jsLists').append( $li.append( $span ) );
It should alert the li's random id on click. Also instead of inline css, add another class for those styles; better, simpler, easier.
Demo: http://jsbin.com/avevim/1/edit (ctrl+enter to refresh and get new id)
Underscore provides a uniqueId function for cases like this. Rather than being tricky with dates and random numbers, it just keeps a global counter and increments it each time the function is called:
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = '' + ++idCounter;
return prefix ? prefix + id : id;
};

jQuery JSON nested loops

I have the following script:
function drawDimensions(divid) {
$.getJSON('dimensions.json', function(data) {
$.each(data, function(index) {
var ppp = $('#' + divid).append("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
$.each(this, function(k, v) {
$('<div>').append(v).appendTo(ppp);
});
});
});
}
drawDimensions('dim');
I'm trying to nest the divs so the values from the first loop will be the parents of the divs on the second loop.
What am I doing wrong? the second loop divs are not nested within the first one but simply appended after the first ones..
The one obvious mistake (may not be the only) is that pppwill still refer to the parent div, not the one you created there.
use appendTo() as you do in inner loop, or have the assignment separate, like:
function drawDimensions(divid) {
var $container = $('#' + divid);
$.getJSON('dimensions.json', function(data) {
$.each(data, function(index) {
var ppp = $("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
$container.append(ppp); // or ppp.appendTo($container);
$.each(this, function(k, v) {
$('<div>').append(v).appendTo(ppp);
});
});
});
}
drawDimensions('dim');
Try and see how it goes, and tell me in comments.
Notes about sample code:
I cached getting the container div jQuery object, since there is only one anyway
Also, used $ as prefix to the variable I used. Just common practice with jQuery objects, not required.
Your ppp is actually a reference to $('#' + divid), not to the newly created (outer) div.
Try this:
var ppp = $("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
ppp.appendTo('#' + divid);

Categories