Jquery loop once or show data once in array of data - javascript

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.

Related

Why variable is undefined inside foreach function?

I have this jQuery function were I create a table:
function propertyView(values) {
// build the table
var frame = '<fieldset id = "propertiesValueArea" style="border: solid 1px #6b6b6b;">';
var content = frame + smallHeader + '<table data-role="table" id="propertiesList"><thead><tr></tr></thead>';
$.each($(values), function () {
var data1 = this.RealValue.FieldValue;
var data2 = this.RealValue.Id;
//create tables row
content += '<tr data-id=' + this.Id + '>';
content += '<td style="vertical-align: inherit;text-align:center;"><label for="">' + this.FieldName + '</label></td>';
if (this.FieldValue.indexOf(',') > -1) {
content += '<td style="text-align:center;"><select>';
this.FieldValue.split(',').forEach(function (item) {
if (data1 === item) //Here data1 is undefined!!!
{
content += '<option selected="selected" value="">' + item + '</option>';
}
else {
content += '<option value="">' + item + '</option>';
}
})
content += '</select></td>';
}
else {
content += '<td style="text-align:center;"><input type="text" id="propFieldName" data-id="' + this.Id + '" value="' + congiValue(this.FieldValue, this.RealValue) + '"/>';
}
content += '</tr>';
});
content += '</table>';
content += '</fieldset>'
return content;
}
Inside outter each function I create 2 variables:
var data1 = this.RealValue.FieldValue;
var data2 = this.RealValue.Id;
I try to create this variable inside inner each:
if (data1 === item) //Here data1 is undefined!!!
But on this row I get this error:
Uncaught ReferenceError: data1 is not defined
Any idea why data1 is undefined?
It can be undefined only because this.RealValue.FieldValue or this.RealValue is undefined
It looks like
var data1 = this.RealValue.FieldValue; //it's value is undefined
this.FieldValue //it's value is undefined
try to
console.log(this.FieldValue)
console.log(data1)
After that you can easily found where you are getting an error and why. Else everything looks fine with your code.
I have encountered similar problem before. It took me several hours to discover the problem. Now that aside there some things which is not clear here.
is the value coming from another function's operation? If
this.RealValue.FieldValue;
is coming from e.g. a result of maybe another function then you would need to use async/await to ensure that the function completes its operation and there is data in this.RealValue.FieldValue before you move on to the next line of code.
Maybe the this.RealValue.FieldValue itself does not have any thing assigned to it outside of the function itself.
In order to help you we would need a complete code. If you think your code is too private then you can go through it by trying what #Negi Rox said earlier.
Put console.log(this.RealValue.FieldValue) at various strategic locations in your code to determine when it was assigned a value.

Jquery is not completing the append of elements - last two are not appeneded

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..

Pull a single item from json and display in html

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();
});

Edit a list of many elements with jQuery

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?

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Categories

Resources