I have like 100 (or more) elements in a list which is very similar to this:
$.ajax({
url:'mysite.it/ajax/list_filter.php',
data:data,
type:'POST'
}).done(function(data){
var reback = $.parseJSON(data);
var people = '';
if(reback.success){
if(reback.showcase){
$.each((reback.showcase),function(index,item){
var exists = $('ul#ul_people_list input[value="'+item.userid+'"]');
if(exists){
exists.parent('li').remove();
}
people += '<li>';
people += '<input type="hidden" class="username" name="username" value="' + item.userid + '"/>';
people += '<a class="show_dtl';
if(item.vip != 0){people += ' vip ';}
people += '" href="usr_dtl">';
people += '<div><img src="'mysite.it/pict_thumbs/' +item.pool_user_pict+ '" style="height: 80px; left: 1px;"></div>';
people += '<label>' +item.username+ '</label>';
if(item.vip != 0){people += '<span class="icon-star"></span>';}
people += '</a></li>';
});
if(refreshType == 2){//if refreshing
$('#people_list ul#ul_people_list').prepend(people);
} else {
$('#people_list ul#ul_people_list').html(people);
}
}
} else {
$('#people_list ul#ul_people_list').html('<li>' + reback.showcase + '</li>');}
});
When I refresh the list (about every 20 seconds) I have to add some element, update some element and delete some element.
I do all this with jQuery.
What is the best way, performance-wise, to do it?
At the moment I use the value attribute (in the second input element) to address the element I want to edit.
Is it better if I change my code to:
<li id="/* userid */">
Of course other suggestions are appreciated?
Related
Currently making a website to index and play movies stored on my hard drive that I've recently pulled off dvds just as a little side project. I have a 'master movie list' JSON file with all the data I need for each movie including the name, video source, video poster source, and genre which I would like to allow the use of placing a movie in multiple different genres.
Currently the problem I'm having is while I'm parsing through the genre list generated its not placing the html in the correct ID that id like it to on the webpage.
For example:
"genre":"comedy,recent,scifi"
I went about it how I thought I should, through getJSON and setting an output variable to which I get the genre value, split to make it an array, and get the element by going through each of them in a loop. Its not placing it in the right place though. The example above would be placed in comedy, recent, scifi, horror, and a few others for some reason and I have absolutely no reason why.
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
var output = '';
var ele = $('');
$.each(data, function(key, val) {
output += '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.html(output);
}
});
});
[ {
"name": "a star is born", "video_src":"/files/movies/A%20Star%20Is%20Born/astarisborn.mp4", "video_poster_src":"https://images-na.ssl-images-amazon.com/images/I/51R-TU6VaTL.jpg", "genre":"recently,romance,drama"
}
] // this is an example of the json
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="genre_box">
<h3>RECENTLY ADDED</h3>
<div class="scroll_box" id="recently"></div>
</div>
<div class="genre_box">
<h3>ACTION</h3>
<div class="scroll_box" id="action"></div>
</div>
<div class="genre_box">
<h3>COMEDY</h3>
<div class="scroll_box" id="comedy"></div>
</div>
Your output variable is being appended to and kept on every iteration of your $.each loop. What you want is to append to the end of $("#action"), $("#comedy"), etc. You should do something along these lines:
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
$.each(data, function(key, val) {
var output = '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (var i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.append(output);
}
});
});
I receive an array from ajax call and build a series of radio boxes using the array's elements. Only some of the radio boxes are appended, not all, eg. out of 4 elements in the array only first two are appended, out of 3 elements only the first is appended.
The array from ajax call is as expected. The for loop works correctly, ie. the text to be inserted is built as expected, yet the append is not appending the expected lot but only some. I've run out of ideas...
here's my html:
<table class="std-table">
<tr>
<td><div id="areas"></div></td>
</tr>
</table>
and javascript:
$(document).on('pagebeforeshow', '#property-details-page', function(){
all_areas = new Array();
var Q001Data = "sql=Q001&dbcall=sql_get_results_array&memid="+<?php echo $member_id?>+"&propid="+<?php echo $property_id?>;
$.ajax({ // ### AJAX to get ALL AREAS on page load ###
url:"pl_process_ajax_call_property_features.php",
type:"POST",
data : Q001Data,
success:function(msg){
$("#areas").html('<fieldset id="all-areas-radio" data-role="controlgroup" data-mini="true"></fieldset>');
all_areas = JSON.parse(msg);
var textToInsert = '';
var i;
for (i = 0; i < all_areas.length; ++i) {
var area = JSON.stringify(all_areas[i][0]);
alert(area+i);
textToInsert += '<input type="radio" class="all-areas" name="property-area" id="' + area + '" value="' + area + '"><label for="' + area + '">' + area + '</label>';
alert(textToInsert);
}
$("#all-areas-radio").append(textToInsert);
$("[type=radio]").checkboxradio();
$("[data-role=controlgroup]").controlgroup().controlgroup("refresh");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Q001!");
},
}); // ### AJAX to get ALL AREAS on page load ###
}); // ### document.on
The alerts in the loop are just to see what's happening inside. The textToInsert is built correctly, but then append is missing out on last two elements.
I've tried to append inside the loop but that made no difference to the outcome. Please help.
You are incrementing your counter too soon. Instead of ++i, try i++
for (i = 0; i <= all_areas.length; i++) {
var area = JSON.stringify(all_areas[i][0]);
alert(area + i);
textToInsert += '<input type="radio" class="all-areas" name="property-area" id="' + area + '" value="' + area + '"><label for="' + area + '">' + area + '</label>';
alert(textToInsert);
}
If using for loop like this:
You are using i < all_areas.length because variable i strats from 0 so you can use i <= all_areas.length;
and also ++i you write pre increment; you can use post increment i++ then you can get all the radio buttons..
I have an array in a JSON file and what I want to do is pull a single entry from the array and display it when the page loads.
I have gotten partway there using this question and answer, however my attempt to adapt this answer causes the output html block to repeat the array items in sequence instead of simply picking one.
Here is a screenshot of what I get:
screenshot of output
I am likely doing something real stupid, and I hope someone can point this out.
My script is as follows:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
$.each(data, function(entryIndex, entry) {
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
});
Any questions just let me know.
Cut this:
$.each(data, function(entryIndex, entry) {
The whole purpose of $.each is to iterate over the entire array, which is the opposite of what you want. You're already defining entry earlier as a random entry from the data.
So you'll have:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
I am using $.get() request to fetch data from Laravel controller and getting array of data in Javascript.
function getSpots1(){
var spots = $('#event-spots1');
spots.empty();
spots.html('<p><i class="uk-icon-refresh uk-icon-medium uk-icon-spin"></i></p>');
var event_id = $("#event-event_id").val();
var event_date = $("#event-date").val();
var code = '';
console.log(event_date);
$.get("/1/users/spots/" + event_id + "/" + event_date + "/date", function(data) {
spots.empty();
console.log(data);
code += '<label for="event_time" class="uk-form-label">Select Time</label><select class="uk-width-1-1" name="event_time" id="event-time">';
$.each(data.spots, function(index, value)
{
code += '<option value="' + value.event_time + '">' + value.event_time + '</option>';
});
code += '</select><p class="uk-form-help-block uk-text-muted">The spot you\'re booking</p>';
code += '</br><div class="uk-margin-bottom"><label for="event_time" class="uk-form-label">Price</label>';
$.each(data.spots, function(index, value)
{
code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />';
});
spots.append(code);
getSpots2();
});
}
I have $.each() jquery method to loop through array of Data. but for second $.each() method, I just need to loop once. I get value.price Multiple times depending on the loop length. For first $.each I need a loop because I have select input field.
Is there a another method instead of $.each to loop once through data variable? I am new and haven't really coded Jquery or Javascript before.
Well you could just get the first object in data.spots like for example data.spots[0].event_time and then you don't have to loop at all.
Less recommended, you could just put a return false; at the end of a loop like for example:
$.each(data.spots, function(index, value)
{
code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />';
return false;
});
which immediately stops the loop.
I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;