I'm using this code to import a CSV into a var using ajax, then, split the informatiĆ³n delimited by the "\n" and then populate a Select Box I have in a form.
The CSV is pretty much flat, just 1 column with several rows. Added an alert to monitor the progress.. it all goes fine except when it comes to populate the combobox, instead of populating the String Content, it populates the number of row, for some reason the array is not recording string but row number.
<script>
$.ajax({
url: 'URL CSV',
success: function(data) {
alert(data);
var splitData=data.split("\n");
for(pn in splitData){
alert(splitData);
$('#Entry_ID').append("<option value=\""+pn+"\">"+pn+"</option>");
}
}
});
</script>
(the form combobox code)
<select name="Entry.ID" id="Entry_ID" aria-required="true"></option>
</select>
Your error is in the "for..in" loop. A code like this:
var arr = ["q", "w", "e"];
for (var i in arr) {
console.log(i)
}
will output:
0
1
2
The for..in loop takes the key of each item in the object and it is assigned to the var. In an array the key is its position.
The method split of String returns an array with all the items. To loop through the splitData array you can:
for (var i = 0; i < splitData.length; i++) {
alert(splitData[i]);
$('#Entry_ID').append("<option value=\"" + splitData[i] + "\">" +
splitData[i] + "</option>");
}
or
splitData.forEach(function (item) {
alert(item);
$('#Entry_ID').append("<option value=\"" + item + "\">" + item + "</option>");
});
Related
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
The json output is some thing like:
{"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}
I need to do an append with each of the received values. The numbers next to them are how many times they exist.
I know it will probably be something with "for each" value, but, since the values and keys of the json response are variable, it's difficult for me how to figure out the way to do it.
I will like that the append order depends on how big the number is. If it's bigger print it on the top, and so on...
for example:
<div id="values">
<p>The value "more" is repeated 5 time(s).</p>
<p>The value "apple" is repeated 3 time(s).</p>
<p>The value "another" is repeated 1 time(s).</p>
...
</div>
Remember! The response can change, the response won't be always apple, another, more, volvo, audi and ford... It can CHANGE!
EDIT:
I can do something with this, but, how do I order them with higher or lower values?
for (var key in interests) {
if (interests.hasOwnProperty(key)) {
console.log(key + " -> " + interests[key]);
}
}
EDIT:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}; // initial data
var interestsValue = []; // data with values
for (var key in data){ interestsValue.push({ name: key, value: data[key] }); } // send data with values
interestsValue.sort(function(a, b){ return b.value - a.value; }); // sort values
console.log(interestsValue); // values ordered from bigger to smaller
First - convert the object to a valid array:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
var arr = [];
for (var key in data)
{
arr.push({ name: key, value: data[key] });
}
Then.... use that array with jQuery, angular, etc... to populate your elements
Enjoy :)
Like this.Loop through your objcet using jquery's $.each method Then append the html into your div with append method.
var obj= {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
text = "";
$.each(obj,function(index,element){
text +=" <p>The value " +index+ " is repeated "+ element + " time(s).</p>";
});
$("#values").append(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
JS fiddle https://jsfiddle.net/uobedcf0/
See UPDATED Fiddle:
https://jsfiddle.net/u1kn6d6L/1/
As mention above first convert object into the array.
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
function sortByValue (data){
var dataArray=[];
for(var key in data){
dataArray.push({name:key ,value :data[key]});
}
dataArray.sort(function(a,b){return b.value- a.value}); //sort it in descreasing order
return dataArray;
}
var text="";
var objArray = sortByValue(data);
$.each(objArray,function(index,object){
text +=" <p>The value " +object.name+ " is repeated "+ object.value + " time(s).</p>";
});
$("#values").append(text)
My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like
What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it
$.get('ajax-subcat?cat_id=' + cat_id, function(data)
{
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
alert(subcatObj);
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
The thing I don't know is how to access the data inside the object. Any ideas?
Try this:
JAVASCRIPT
for (var i = 0; i < data.length; i++) {
console.log(data[i].subcategoryid);
}
Assuming that you have a select element in markup:
<select id="mySelectElement"></select>
Try this to iterate the object and fill the combo box:
$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
// Get a reference to the target element
var selectTarget = $('#mySelectElement');
// Iterate over the response data
for (var i in data) {
// For every object in array, append a new option element
selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
}
});
For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.
_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'
I'm fine with using javascript or jquery
I added in another column from the database table to get returned and what I currently see is
122461,4876192
As now I have 2 records
So with that is shows
$.each(alldata.Data, function (index, query) {
strData += "<td>" + query + "</td>";
}
That is spitting out 122461,4876192 how do I use "query" for separation?
I want to end up doing this
<td>122461</td><td>4876192</td>
EDIT: the picture you showed is showing an array of arrays. The reason you are getting comma separated values is because the variable query is actually an array, so when you join it with a string, JS is just listing the values of the subarray in CSV format.
Personally, I think you don't even have to use jQuery for this task, sometimes it's a lot easier to use a couple of nested for loops. You have to loop through the main array, and then each of the subarrays and join them inside of <td> tasks. After that, you can use jQuery for anything you want to do with the elements.
var strData = "";
if (allData.Data) {
for (var i = 0; i < allData.Data.length; i++) {
if (allData.Data[i]) {
for (var j = 0; j < allData.Data[i].length; j++) {
strData += '<td>' + allData.Data[i][j] + '</td>';
}
}
}
}
However, if you really want to use the jQuery each function, you can do
var strData = "";
if (allData.Data) {
$.each(allData.Data, function(i, query) {
// Note this will skip everything that equals to false in JavaScript
// not just null, for example, "", false, 0, etc...
if (!query) return;
$.each(query, function(j, value) {
// See note above
if (!value) return;
strData += '<td>' + value + '</td>';
});
});
}
There's a variety of shortcuts you can take using built-in array functions, such as join as #zan suggested in his answer.
EDIT 2: Added null checks
EDIT 3: Added null checks to jQuery
What you need is
var strData = ''
$.each(alldata.Data, function (index, query) {
strData += "<td>" + query.join('</td><td>') + "</td>";
})
console.log(strData)
Why That is spitting out 122461,4876192 how do I use "query" for separation?
Because you are concatenating Array with String
"myString" + [1,2,3,4] + "otherString"
will give you this output
"myString1,2,3,4otherString"
Try this:
If query is string:
$.each(alldata.Data, function (index, query) {
strData +='<td>'+query.split(',').join('</td><td>')+'</td>';
}
if Query is array then use this:
$.each(alldata.Data, function (index, query) {
strData +='<td>'+query.join('</td><td>')+'</td>';
}
This will also works when you have more the 2 elements in array
I have a for loop that GETs a json array and populates it in a table along with another list's variables. My problem is I am not able to access i inside the get method. But I have mylist and all its contents inside. I tried binding the function to a variable i using bind(this,i) but that says .getJSON() is not a function. Here's the relevant code.
var mylist = ["a", "b", "c"]
for (i = 0; i < mylist.length; i++) {
urlstr = "/" + mylist[i]; // Generate url
$.getJSON(urlstr, function(data) {
html = "<tr><td>" + mylist[i] + "</td><td>" + data.string[0] + "</td></tr>";
$("#tableresult").append(html); //this returns undefined for mylist[i]
console.log(i); //this returns 3 which is the length of list
});
}
In short I need the variables outside getJSON be accessible within getJSON.
Can someone please help? Thanks and regards.
This should be no different from binding the loop variable in practically any other loop. Since you are working with an array, the cleanest approach is to use Array#forEach:
var mylist = ["a", "b", "c"];
mylist.forEach(function (item) {
var urlstr = "/" + item;
$.getJSON(urlstr, function(data){
var html = "<tr><td>" + item + "</td><td>" +
data.string[0] + "</td></tr>";
$("#tableresult").append(html);
console.log(item);
});
});
please ensure your php return data is json.
for example:
$data['something'] = 'data';
echo json_encode($data);
and using function for get index (i):
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});