JQuery Mobile collapsible does not apply to div - javascript

I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.

#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>

Related

Uncaught Reference Error when trying to pass a function through a button in JavaScript?

I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?
JS File:
let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
console.log('ok');
type = randomstring;
console.log(type);
}
let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
str = str +
'<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);
document.getElementById('navbar').innerHTML = str;
HTML File(includes the rest of the program)
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1">
<meta charset="utf-8">
<style>
#map {
height: 75%;
width: 75%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script src = getlocation.js></script>
<!-- this implements the navbar-->
<div id="navbar"></div>
<script type = "module" src = navbar.js></script>
<!-- this implements the map-->
<div id="map"></div>
<script src = index.js> </script>
<!-- this implements the list-->
<div id="list"></div>
<script type = "module" src = rankedstores.js></script>
<script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
&callback=initMap"></script>
</body>
</html>
Looks like you just had some errors when building str. Try this
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
let str = '<div class="topnav">';
for (let count = 0; count < typearray.length; count++) {
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "</div>";
console.log(str);
use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
console.log('ok');
type = randomstring;
console.log(randomstring);
}
let str = '<div class="topnav" />';
for(let count = 0; count < typearray.length; count++){
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str = str + '</div>' +
'</div>';
console.log(str);
document.getElementById('navbar').innerHTML = str;
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1">
<meta charset="utf-8">
<style>
#map {
height: 75%;
width: 75%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script src = getlocation.js></script>
<!-- this implements the navbar-->
<div id="navbar"></div>
<script type = "module" src = navbar.js></script>
<!-- this implements the map-->
<div id="map"></div>
<script src = index.js> </script>
<!-- this implements the list-->
<div id="list"></div>
<script type = "module" src = rankedstores.js></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2c7P_IihiITITslXAk-wWy9z067xjFQU
&callback=initMap"></script>
</body>
</html>
use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
Just for understanding purpose:
The problem here is that a html attribute value has to be wrapped around single or double quotes. With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:
<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>
to fix this either use double and single quotes:
str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";
or use template literals (already mentioned by the other answers):
str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
template literals explanation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Modified Code Snippet
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(event) {
type = event.target.getAttribute("type");
console.log(type);
}
let navHtml = document.createElement("div");
for (let count = 0; count < typearray.length; count++) {
let btn = document.createElement("button");
btn.setAttribute("type", typearray[count]);
btn.setAttribute("title", typearray[count]);
btn.innerText = typearray[count];
btn.addEventListener("click", changeType);
navHtml.appendChild(btn);
}
document.getElementById("navbar").appendChild(navHtml);

I am developing duolingo type sentence practice in javascript. I have implemented it but it needs more improvement

I have used following code to develop sentence grammar practice. When I click button then order should to maintained. I want it when button clicked then it should hide but after click on top button again show up.
Move sentence to left if there is blank. Also show button again if words clicked again.
Should using only buttons for showing at top also at bottom?
<html>
<head>
<title>
</title>
</head>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for(i=0;i<senArr.length;i++)
{
//alert(senArr[i]);
dashElement += "<div onclick='funDiv(this.id);' style='display: inline'" + "id = dashid" + i + ">" + '__ ' + '</div>';
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
//var dashID = document.getElementById("dashid0").innerHTML;
//var dash1 = document.getElementById("val");
//dash1.innerHTML= dashID;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='fun(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var ii = 0;
function funDiv(clicked){
//alert(clicked);
var inText = document.getElementById(clicked).innerHTML;
document.getElementById(clicked).innerHTML = " __ " ;
ii--;
}
function fun(clicked){
//alert(clicked);
document.getElementById(clicked).style.display = "none";
document.getElementById("dashid" + ii).innerHTML = document.getElementById(clicked).innerHTML + " ";
//document.getElementById(clicked).remove();
ii++;
}
</script>
</script>
</body>
</html>
How about something like this?
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for (var i = 0; i < senArr.length; i++) {
dashElement += `<div onclick='dashClick(this.id);' style='display: inline' id=dash${i}> __ </div>`;
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var picked = 0;
function dashClick(clicked) {
const dash = document.getElementById(clicked);
dash.innerHTML = " __ ";
const btn = document.getElementById(`btn${dash.btnId}`);
btn.style.display = "inline";
picked--;
}
function btnClick(clicked) {
var btnId = clicked.replace('btn', '');
document.getElementById(clicked).style.display = "none";
const dash = document.getElementById("dash" + picked)
dash.innerHTML = document.getElementById(clicked).innerHTML + " ";
dash.btnId = btnId;
picked++;
}
</script>
</body>
</html>
I have implemented it using appendChild and remove functions of JavaScript.
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
var btnElements = "";
for (var i = 0; i < senArr.length; i++) {
btnElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'> " + senArr[i] + ' </button>';
}
var container = document.getElementById("container");
container.innerHTML = btnElements;
var picked = 0;
function dashClick(clicked) {
//console.log(clicked);
var buttons = document.getElementsByTagName('button');
var dash = document.getElementById("dash");
dashChild = dash.childNodes;
console.log(document.getElementById(clicked).innerText);
for(i=0;i<senArr.length;i++){
if(document.getElementById(clicked).innerText.trim() == buttons[i].innerText.trim()){
//console.log("Match");
buttons[i].style.opacity = "1";
buttons[i].style.pointerEvents = "auto";
}
}
document.getElementById(clicked).remove(); // remove clicked text
}
// Button click
function btnClick(clicked) {
var dashElement = document.createElement("div");
var text = document.getElementById(clicked).innerText;
dashElement.style.display = "inline";
dashElement.innerHTML = "<div style='display: inline' onclick='dashClick(this.id);' id=" + picked +"> " + text + " </div>"; // add text at top of button
document.getElementById("dash").appendChild(dashElement);
picked++;
document.getElementById(clicked).style.opacity = "0"; //hide button that has been clicked
document.getElementById(clicked).style.pointerEvents = "none";
}
</script>
</body>
</html>

How to add select filtering for column values in javascript DataTables

I'm using javascript DataTables to display a csv file on a webpage. Below is my
javascript file:
var CsvToHtmlTable = CsvToHtmlTable || {};
CsvToHtmlTable = {
init: function (options) {
options = options || {};
var csv_path = options.csv_path || "";
var el = options.element || "table-container";
var allow_download = options.allow_download || false;
var csv_options = options.csv_options || {};
var datatables_options = options.datatables_options || {};
var custom_formatting = options.custom_formatting || [];
$("#" + el).html("<table class='table table-striped table-condensed' id='" + el + "-table'></table>");
$.when($.get(csv_path)).then(
function(data){
var csv_data = $.csv.toArrays(data, csv_options);
var table_head = "<thead><tr>";
for (head_id = 0; head_id < csv_data[0].length; head_id++) {
table_head += "<th>" + csv_data[0][head_id] + "</th>";
}
table_head += "</tr></thead>";
$('#' + el + '-table').append(table_head);
$('#' + el + '-table').append("<tbody></tbody>");
for (row_id = 1; row_id < csv_data.length; row_id++) {
var row_html = "<tr>";
var color = "red";
//takes in an array of column index and function pairs
if (custom_formatting != []) {
$.each(custom_formatting, function(i, v){
var col_idx = v[0]
var func = v[1];
csv_data[row_id][col_idx]= func(csv_data[row_id][col_idx]);
})
}
for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
if (col_id === 2) {
row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
}
else {
row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
}
if (parseFloat(csv_data[row_id][2]) <= 1 && parseFloat(csv_data[row_id][2]) > 0.7) {
color = "red";
}
else if (parseFloat(csv_data[row_id][2]) <= 0.7 && parseFloat(csv_data[row_id][2]) >= 0.5) {
color = "orange";
}
else {
color = "yellow";
}
}
row_html += "</tr>";
$('#' + el + '-table tbody').append(row_html).css("background-color", color));
}
$('#' + el + '-table').DataTable(datatables_options);
if (allow_download)
$("#" + el).append("<p><a class='btn btn-info' href='" + csv_path + "'><i class='glyphicon glyphicon-download'></i> Download as CSV</a></p>");
});
}
}
And below is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CSV to HTML Table</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/dataTables.bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<h2>CSV to HTML Table</h2>
<div id='table-container'></div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.csv.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="js/csv_to_html_table.js"></script>
<script type="text/javascript">
function format_link(link){
if (link)
return "<a href='" + link + "' target='_blank'>" + link + "</a>";
else
return "";
}
CsvToHtmlTable.init({
csv_path: 'data/fatty_acid_profiles.csv',
element: 'table-container',
allow_download: true,
csv_options: {separator: ','},
datatables_options: {"paging": false},
custom_formatting: [[4, format_link]]
});
</script>
</body>
</html>
My webpage currently looks like this:
I want to know is it possible in DataTables that for 2nd & 3rd columns, I get a Filter along with the column name so that we can select for which specific values we want to view data for, something like what we have in Excel (using Sort & Filter)?? Please help!!
Yes, it is possible with a customized solution.
You need to read all columns and add distinct members to dropdowns like this.
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
});
}
});
});
By using column().search() functionality, you will have a column based filter with dropdowns. You can move dropdowns from header to footer by changing .appendTo($(column.header()).empty()) to .appendTo($(column.footer()).empty()).
Examples:
jsFiddle (header dropdowns)
jsFiddle (footer dropdowns)

Error when trying to load words from JSON

I have this problem where my words of JSON won't load into my Webpage, the images do work already, fortunally..
I already have the images that needed to be loaded trough JSON into my Webpage.
I still need some words to load trough JSON into my Webpage,
{"main_object": {
"imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
"wordsJ": ["næb", "kat", "æg", "mel", "mælk", "pas", "ske", "te"]
}
}
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
header {
height: 5%;
}
body {
background-color: #f0f0f0;
}
.container {
height: 90%;
}
.images img {
height: 100px;
width: 100px;
}
footer{
height: 5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sleepopdracht</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/css.css">
</head>
<body>
<header>
</header>
<div class="container" id="container"><div class="images" id="images"></div>
<div class="words" id="words"></div>
</div>
<footer>
</footer>
<script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>
In the Javascript you can see that I loaded the words a little like the images, as far as I know it should just work, but the console reports an
Uncaught ReferenceError: Invalid left-hand side in assignment ~ jquery.min.js:4
I can't seem to figure out te source of the problem, neighter do I know how to solve it full.
It seems that The error exists even if i commend the Words loop out, The Error existed already without the code calling the words JSON. But now the problem still is that I can't find the source of the problem, if I found it, it is probably easy to solve. Since the last time I checked, the code ran perfectly without the Words Loop
I see that you havn't defined imagesJ and wordsJ
var imagesJ;
var wordsj;
And you need to do something like this
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
Final File
var jsonData = "noJson";
var hr = new XMLHttpRequest();
var imagesJ;
var wordsj;
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Try changing this code:
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
to:
var words = document.getElementById('words')
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
I found that the problem was in
document.getElementById('images') = html;
this was wrong, first I didn't call html at all so I made a var after console log of html with an empty string.
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
The var html2 is for the words.
then my document.getElementById was not complete (that was the Error)
This was the proper code for the document.
document.getElementById('images').innerHTML = html;
Then I had,
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
wich needed to be this,
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
So my full code then was,
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
for(i = 0; i < imagesJ.length; i++) {
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
//images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images').innerHTML = html;
//$('#images').append(html);
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>'+wordsJ[i]+'</span>';
}
document.getElementById('words').innerHTML = html2;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Altough I still don't have the words in my browser, the Error is resolved.
Thanks Everyone :D Happy programming!

problems trying to get tweets from different zip codes

I am trying to get tweets from different zip codes.For doing this, I am using latitude and longitude values for each zip code. So far I want to get 3 tweets for each zip code(I have 2 zip codes), but it is working only for one zip code.
Any suggestion will be appreciated. Thank you in advance!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat=[41.9716,42.0411];
var lng=[-87.7026,-87.6900];
$(document).ready(function() {
for(var i=1; i<2; i++)
{
$.getJSON('http://search.twitter.com/search.json?q=business&geocode='+lat[i]+','+lng[i]+',5mi&lang=en&callback=?', function(data) {
var data = data.results;
var html = "";
for(var j=0; j<3;j++){
html += "<div style='width:600px;border:solid thin blue'><img src='"+data[j].profile_image_url+"'/><a href='http://twitter.com/" + data[j].from_user + "'>#"+ data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content'+i).html(html);
}); }
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
I found 2 problems with your code:
1) If you want to iterate 2 times, your for function should be like this: for (var i = 0; i < 2; i++)
2) You must have in consideration that the function that gets called in $.getJSON runs asynchronously, so when that function gets called the for will have already finished, therefore you can't use the i value with that purpose inside that function.
So, after correcting those 2 things in your code you should be able to get what you want. Try with something like this:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat = [41.9716, 42.0411];
var lng = [-87.7026, -87.6900];
var count = 1;
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$.getJSON('http://search.twitter.com/search.json?q=business&geocode=' + lat[i] + ',' + lng[i] + ',5mi&lang=en&callback=?', function (data) {
var data = data.results;
var html = "";
for (var j = 0; j < 3; j++) {
html += "<div style='width:600px;border:solid thin blue'><img src='" + data[j].profile_image_url + "'/><a href='http://twitter.com/" + data[j].from_user + "'>#" + data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content' + count++).html(html);
});
}
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
</html>

Categories

Resources