Im trying to access random quotes through an API using Jquery. I am very new to this so I'm sure there is a simple solution that I cannot see. Basically this is my HTML code:
<div class="col-md-6">
<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
</div>
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8 show boxed text-center">
Text
</div>
<div class="col-md-2">
</div>
</div>
My JS is this:
$(document).ready(function() {
$("#quoteClick").on("click", function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
json.forEach(function(x) {
html += "<div class = 'quote'>";
html += "<h3 '" + x.quoteText + "' "+ "'>";
html += "</div>";
});
$(".show").html(html);
});
});
});
When I use console.log(json) I can print the object I'm querying from, but when I actually try to fish out a quote and print it on my web page nothing happens. I am using codepen.
You shouldn't be iterating over the object you get from the API. If you look at a single API call, one result I got looked like this:
{
"quoteText": "To be thoughtful and kind only takes a few seconds compared to the timeless hurt caused by one rude gesture.",
"quoteAuthor": "Byron Pulsifer",
"senderName": "",
"senderLink": "",
"quoteLink": "http:\/\/forismatic.com\/en\/4255d6ba93\/"
}
You just need to drop the forEach call, and your code will work.
Also (gavgrif noted this first in their answer), your HTML is malformed - you should have the text inside the h3.
This should be better:
$(document).ready(function() {
$("#quoteClick").click(function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
html += "<div class = 'quote'>";
html += "<h3>" + json.quoteText + "</h3>";
html += "</div>";
$(".show").html(html);
});
});
});
Related
I am trying to tweet text I get from a function executing a getJSON command, the tweet button I created opens twitter but with no text, I want it to automatically "paste" the quote the webpage is currently displaying. My basic html code is the following:
<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
<div class="col-md-8 show boxed text-center"> Text </div>
<div class="col-md-5 text-center author"> auth
</div>
<a class="tw-button" href="https://twitter.com/intent/tweet/?text=" data-size="large" target="_blank">
<button type="twbutton" class="btn btn-primary">Tweet quote</button>
</a>
My JS:
$(document).ready(function() {
gQuote();
function gQuote() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en",
function(data) {
var Quote = data.quoteText;
var Author = data.quoteAuthor;
var quoteShow = ""
var quoteAuthor = ""
quoteShow += "<h3 class='text-center'>" + Quote + "</h3>"
quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>"
$(".show").html(quoteShow);
$(".author").html(quoteAuthor);
});
};
$("#quoteClick").on("click",function() {
gQuote();
});
$(".tw-button").click(function(){
$(this).attr("href",'https://twitter.com/intent/tweet/?text='+ Quote);
});
});
I understand that the Quote variable was created within the previous function and I am not clear as to how I can "carry" it towards the twitter button.
I am using codepen so "target:_blank" is a must.
The Quote variable is local to the callback in the $.getJSON.
One (and the simplest) of the solutions is shifting the 'var Qoute' declaration to the callback of the $(document).ready callback, so that it is accessible to the '$(".tw-button").click' callback through the scope chain during the right hand search. Though, this is not very good for larger-scaled code.
$(document).ready(function() {
gQuote();
var Quote; //Declare variable here
function gQuote() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(data) {
Quote = data.quoteText; //Set it here
var Author = data.quoteAuthor;
var quoteShow = ""
var quoteAuthor = ""
quoteShow += "<h3 class='text-center'>" + Quote + "</h3>"
quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>"
$(".show").html(quoteShow);
$(".author").html(quoteAuthor);
});
};
$("#quoteClick").on("click",function() {
gQuote();
});
$(".tw-button").click(function(){
$(this).attr("href",'https://twitter.com/intent/tweet/?text='+ Quote);
});
});
If I'm not mistaken all you need to do is declare your variables Quote and Author outside gQuote() function. Inside gQuote() you can assign them whatever you wish and pass their latest values to $(".tw-button").click() event. Make sure you got JSON object and parsed data from it right.
I made something similar as freecodecamp project. Have a look here if you have difficulties.
I need to disable the elements of class "gcf_crud" that are into a variable.
My wrong code is:
var defText = ''+
' <div class="form-group col-md-12">'+
' <h4 id="minimum-setp">{{title}}</h4>'+
' <input type="text" class="form-control gcf_crud" id="txtUsuari" value="{{data}}"/>'+
' </div>';
var defTextDisabled = $(defText).find('.gcf_crud').prop('disabled', true);
With this code i'm obtaining only the input but I need all the original html.
How may I do it right?
Regards,
Seak
Your defTextDisabled variable only returns the input because of .find('.gcf_crud').
But it seems that you need a reference (variable) to a jQuery object containing all the elements. In order to do that, break down your process in steps:
var defText = '<div class="form-group col-md-12">'
+ '<h4 id="minimum-setp">{{title}}</h4>'
+ '<input type="text" class="form-control gcf_crud" id="txtUsuari" value="{{data}}"/>'
+ '</div>',
$defText = $(defText); // Save the entire thing here
// Now, you can disable the input
$defText.find('.gcf_crud').prop('disabled', true);
// And use the whole content
$('body').append($defText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
Add the gcf_crud class to the main div.
Ive been desperately trying to get this to work.
Iknow there are probably better ways to do this other than the way I am trying but its for an assignment and has to be done this way.
I am creating a simple shopping cart/ the cart does not have to add a total just get the items inside of the panel (if anyone knew how to add the price also that would be brilliant but not 100% necessary)
So I have displayed items of json using json and ajax, on page ready the items are on show as so (there are about 12 items):
so I have the panel hidden, when the user clicks on a button (the blue button) I want the json information and the json price to appear inside the panel.
here is a snip of one of the items from my json file (which is called result.json:
{
"appleitems":[
{
"Product_id":"Iphone5",
"Information":"Iphone 5 64GB",
"Imgpath":"image/iphone5.jpg",
"Price":"200.00"
}
]
}
This ishow my items are displayed:
$.getJSON('iproducts.json',function(products){
var output = "";
$.each(products.appleitems, function(i, product) {
output +=
"<div class=\"col-xs-12 col-sm-6 col-md-3\"><div class='panel panel-default'><div class='panel-footer'><h4 class='text-center'>"
+ products.appleitems[i].Product_id
+ "</h4></div>" + "<img src ='" + products.appleitems[i].Imgpath + "' style='width:100%;height:250px; display: block;' id='appleinfo_"
+ products.appleitems[i].Product_id + "' /><h5 class='text-center'>" + products.appleitems[i].Information
+ "</h5><div class='panel-footer'>`<button class='btn btn-primary btn-block' id='btnadd'>£" + products.appleitems[i].Price+"</button>`</div></div></div>";
});
$("#container").html(output);
});
and you will notice the button that I want clicked to display the json is btnadd:
<button class='btn btn-primary btn-block' id='btnadd'>£" + products.appleitems[i].Price+"</button>
so when the user clicks btn add I want the json "information" and "price" to display inside of the pannel cart:
<div class="panel panel-default">
<div class="panel-body" id="cart"></div>
I have started the script for this:
$(document).ready(function() {
//Hide alert when page loads
$("#cart").hide();
//get the item into the panel
$("#btnadd").click(function(event){
$.getJSON('result.json', function(add) {
...
});
});
});
First of all, You are having same Id value for all the buttons(inside the loop). Duplicate Id's are not valid. So may be you can remove that and add a css class to the button for the jQuery selection. Also i would recommend keeping the price and information in HTML5 data attributes on the button for easier read.
var output ="";
$.each(products.appleitems, function(i, product) {
output += "<div><div>"
output +="<button class='btn btn-primary btn-block addBtn' data-info='"+
product.Price +"' data-price='"+
product.Information +"'>£" + product.Price+"</button>";
output +="</div></div>";
});
And listen to the click event on this specific css class
$(function(){
$(document).on("click",".addBtn",function(e){
e.preventDefault();
var _this=$(this);
var c=_this.data("info") + " " +_this.data("price");
$("#cart").html(c);
});
});
Here is a working sample
I'm developing a webpage with a form that is created dynamically by means of javascript (jquery). For each (repetitive) set of form elements a Show/hide function is added to show and hide the elements, and I dont get this show/hide code working - I suspect the error is located as indicated within the code below, and I think I struggle to put the quotes at the right place (?) The console indicates an error "Uncaught SyntaxError: Unexpected token } " which I dont understand; when excluding the suspected erroneous line there are no further errors and I dont see where this '}' shows up where it's not supposed to show up.
Javascript code:
function ShowHide(id) {
$(id).toggle();
}
$(document).ready(function () {
var buildform = function () {
var form ='<div id="form">'
for (var i = 0; i < 2; i++) {
form += '<div id="filename"' + i + '> Document </div> </td>';
//error in next line (?)
form += '<button onclick="ShowHide(\'#filename'+ i +'\')"> Show/hide document </button> </td> </tr>';
} //for i
form += '</div>'; //id="form"
console.log('FORM: '+form);
return
} //buildform()
$("#wrapper").append(form);
}); //$(document).
HTML code:
<div id="wrapper"></div>
Output by javaconsole():
<div id="form"><div id="filename"0> Document </div><button onclick="ShowHide('#filename0')"> Show/hide document </button></div><div id="filename"1> Document </div><button onclick="ShowHide('#filename1')"> Show/hide document </button></div>
You're quotes are wrong.
form += '<td> <button onclick="ShowHide(\'#filename'+ i + '\')"> Show/hide document </button> </td> </tr>';
I matched the quotes in parenthesis, and escaped them with \. Also, you're saving your created html, but never show anywhere that it would actually output the html to the page. You need to actually output the information created. For example:
The HTML:
<div ="outputContainer"></div>
Inside your function:
$("#outputContainer").html(form);
Escape the quotes correct
Please change the line:
form += '<td> <button onclick="ShowHide("#filename'+ i +')"> Show/hide document </button> </td> </tr>';
to this:
form += '<td> <button onclick="ShowHide(\'#filename'+ i +'\')"> Show/hide document </button> </td> </tr>';
^ ^
My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!