Trying to parse a json with several arrays inside - javascript

This is my Index.html
<div id="#here">
</div>
<script type="text/javascript">
$( document ).ready(function() {
$.getJSON("https://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_ETH&depth=30", function(data){
var x = data.asks
$.each(x, function(index, item) {
//console.log(item);
$('#here').append("<p>"+ item +"</p>");
});
});
});
</script>
i'm just trying to parse a json an put inside a p.
in the console the script runs ok
help guys, pleas

item is an array so you need to access the array element using brackets notation like so:
item[0]
You also want to remove the # symbol from the id attribute of your div element.
The id attribute value must begin with a letter.
So this should work.
--HTML--
<div id="here"></div>
--JS--
$( document ).ready(function() {
$.getJSON("https://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_ETH&depth=30", function(data) {
var x = data.asks;
$.each(x, function(index, item) {
var $paragraph = $('<p>');
$paragraph.text(item[0])
$('#here').append($paragraph);
});
});
});

Related

I am calling a jquery function from html select and accessing some object in jquery function. but is comes undefined

here is my jquery function
<script type="text/javascript">
$('#branddrop').change(function getModels(){
console.log('entered')
brand = $(this).val();
console.log(brand);
console.log("http://localhost:8006/api/models/" + String(brand['name']));
$.get("http://localhost:8006/api/models/",
function(data) {
var models = $('#model');
models.empty();
$.each(data, function(i, value) {
models
.append($("<option></option>")
.attr("value",value.name)
.text(value.name));
});
});
});
</script>
I am able to console the brand as
{"id":5,"name":"LeEco","created_at":null,"updated_at":null}
but when console the brand['name'] i get undefined.
Looks like the brand variable holds the string value '{"id":5,"name":"LeEco","created_at":null,"updated_at":null}'
You might have to parse the string into an object as follows:
var brandObj = JSON.parse(brand);
brandObj['name'] // should work

How to set the HTML select options from a json

I got one external .json file, in which a arry is defined as:
var words = [
"a",
"able",
"about",
"account",
"acid",
"across",
"act",
"addition"]
My plan is to import in the .json file via jquery, and then use the values in the array word as the option in a select object.
My understanding is:
<div>
<select size="7" class="selection"></select>
</div>
<script>
$(document).ready(function () {
$.getJSON("words-small.json", function (result) {
$.each(result, function (i, word) {
$(".selection").html("<option>word</option>");
});
});
});
</script>
or:
<script>
$(document).ready(function () {
$.getJSON("words-small.json", function (result) {
html = ''
for (i = 0; i < results.length; i++) {
html += "<option value=" + result[i] + ">" + result[i] + "</option>";
};
document.getElementById("myselect").innerHTML = html;
});
});
</script>
But neither works here. Please tell me how to fix that.
Your .json-file needs to be like this:
[
"a",
"able",
"about",
"account",
"acid",
"across",
"act",
"addition"
]
Then either of the scripts should work. (First one with one small adjustment)
<div>
<select size="7" class="selection"></select>
</div>
<script>
$(document).ready(function () {
$.getJSON("words-small.json", function (result) {
$.each(result, function (i, word) {
$(".selection").append("<option>"+word+"</option>");
});
});
});
</script>
Remember that a .json-file should only contain JSON. Not javascript which is what you had.
You have some typos in your code.
Assuming that you have valid json and parsed words array
var words = [
"a",
"able",
"about",
"account",
"acid",
"across",
"act",
"addition"];
$.each(words, function (i, word) {
$(".selection").append("<option value='"+word+"'>" + word + "</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select size="7" class="selection"></select>
</div>
For your first attempt, you're doing:
$(".selection").html("<option>word</option>");
You should be using something like append, and also make sure you take "word" out of the quotes:
$(".selection").append("<option>" + word + "</option">);
.html() just replaces the data contained within the HTML element, whereas .append() will add them to the end.
This is the issue if you're only getting one value returned.
It looks like in your JSON object you have the data defined in a variable, instead it should just be:
[
"a",
"able",
"about",
"account",
"acid",
"across",
"act",
"addition"
]
this work for me:
$.each(words, function (i, word) {
items+="<option>"+word+"</option>";
});
$(".selection").html(items);
You have several things that need to be fixed. One, is that .html() replaces the innerHTML, doesn't add to it. So, you need to build all the options and then set them. I also, as you had in the second script, put the value of the word as the option value. Note, the inner quotes are also needed. Furthermore, your jQuery of ".selection" will do this to all objects designated with the "selection" class, whereas, in your second script, you seemed to want to only assign one element with an id of "myselect".
<div>
<select size="7" class="selection"></select>
</div>
<script>
$(document).ready(function () {
$.getJSON("words-small.json", function (result) {
var html = "";
$.each(result, function (i, word) {
html += "<option value='"+word+"'>"+word+"</option");
});
$(".selection").html(html);
});
});
</script>
You can extend jQuery. The best thing about this approach is you can reuse these extensions when needing to clear or fill a select. Just pass it an array.
$.fn.clearSelect = function() {
return this.each(function() {
if (this.tagName == 'SELECT')
this.options.length = 0;
});
}
$.fn.fillSelect = function(data) {
return this.clearSelect().each(function() {
if (this.tagName == 'SELECT') {
var dropdownList = this;
if (data.length > 0) {
this.disabled = false;
}
$.each(data, function(index, optionData) {
var option = new Option(optionData, optionData);
dropdownList.add(option, null);
});
}
});
}
This extension will allow you to pass your data directly to the select like this
$("#myselectid").fillselect(["a","able","about","account","acid","across","act"]);
I have not tested this, but the snip-it should give you the general idea.
But in your example you could call the extensions this way:
$(document).ready(function () {
$.getJSON("words-small.json", function (result) {
$(".selection").fillSelect(result);
}
});
Just tested and edited the snipet. Test is located here https://jsfiddle.net/4wmj8pkk/

Count html elements in ajax returned data

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!
Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});
$('.blah','context').length
Replace context by object in which you want to search

Get Item Count for a Specific View

Is there a piece of jQuery or JavaScript that I can run that will allow me to create a Content Editor Web Part that has "This is the number of list items: XYZed."
I've tried this but it is not working:
http://www.martinhatch.com/2010/09/how-to-achieve-count-on-large.html
The one I tried was the 4'th attempt. If someone could help me that would be fantastic.
try these solutions/posts in the given order.
https://sharepoint.stackexchange.com/questions/5477/getting-a-count-of-list-items-in-a-list-via-ecmascript
https://sharepoint.stackexchange.com/questions/18050/how-do-i-get-the-number-of-items-in-a-list
http://www.codeproject.com/Questions/266281/jQUERY-TO-GET-COUNT-OF-TOTAL-ITEMS-EXISTED-IN-SP-L
It worked for me. All I had to do was create the grouped view and put the url into the code. Tho I used quotes
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//////////
// you will need to change this URL
var url = "http://sppos/Lists/Statistics/Grouped.aspx";
//////////
var groupings = [];
$.get(url, function(data) {
$(data).find("tbody[id^=titl][groupString] > tr > td").each(
function(index, value){
groupings.push($(this).text());
}
);
$("#placeholder").append("<ul></ul>");
$.each(groupings, function(index, value){
$("#placeholder ul").append("<li>" + value + "</li>")
});
});
});
</script>
<div id="placeholder"></div>
After testing, no quotes doesn't work, which may be the cause of some grief

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

Categories