I'm practicing JQuery and I wanted to create some images from JSON data.
I'm using element.attr(attr,value) and it's working nicely with the src attribute but no matter what I can't add any other attributes to my img tag and I don't know why. You can see that I'm trying to add one id but it doesn't work.
Here is my JS code :
$.ajax({
url: "http://ddragon.leagueoflegends.com/cdn/7.5.1/data/en_US/champion.json",
type: 'GET',
dataType: 'json',
data: {},
success: function(response){
var i = 1;
$.each(response.data, function (champion, infos) {
$.each(infos, function (infoKey, infoValue) {
var image = $("<img class='champion-icon'>");
if(infoKey == "id"){
image.attr('id', infoValue);
}
if(infoKey == "image"){
image.attr('src', "http://ddragon.leagueoflegends.com/cdn/7.5.1/img/champion/" + infoValue['full']);
image.appendTo("#champions");
if(i == 14){
$("<br>").appendTo("#champions");
i = 0;
}
i++;
}
});
})
}
});
Related
I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
This page has images and these images must be hidden in load time, after the page receives parameter value from another aspx page(without clicking any button), an image shows based one parameter value. This code can receive data successfully but how to use parameter value to hide and show an image?
HTML:
<input type="button" id="mybutton" />
<script>
$('#mybutton').click(function () {
$.ajax({
url: 'About.aspx',
dataType: 'text',
type: "GET",
success: function(data)
{
var result = $.trim(data);
if (result = 2) {
$("image1").show();
} else {
if (result = 3) {
$("image2").show();
}
}
}
});
});
</script>
<div id="graphic">
<img id="gate1" src="Img/Fully Close Green.png" />
<img id="gate2" src="Img/Fully Close Red.png" />
</div>
try this code hide the images on document ready event or set display:none using css class and then user id of images with image1 and image2, the # tag is used to access id of any element and . used for class for more chcek This:-
$(function () {
$('#graphic img').hide();
$.ajax({
url: 'About.aspx',
dataType: 'text',
type: "GET",
success: function (data) {
var result = $.trim(data);
if (result == 2) {
$("#gate1").show();
} else if (result == 3) {
$("#gate2").show();
}
//you can put more options here or just use else condition instread of else if
}
});
});
You have incorrect comparison logic. Use == or === instead of just =.
Also, study jQuery selectors. Use the elements' IDs.
if (result == 2) {
$("#gate1").show();
} else {
if (result == 3) {
$("#gate2").show();
}
}
Are you going to hide all & show only the one matched with the "result" value?
$('#mybutton').click(function () {
$.ajax({
url: 'About.aspx',
dataType: 'text',
type: "GET",
success: function(data)
{
var result = $.trim(data);
// Hide all
$('div#graphic img').hide();
// Show matched one
$('#gate' + result).show();
}
});
});
I don't know why the selector jquery doesn't accept a variable.
function myfunction()
{
$.ajax({
url: "/file.php", dataType: "json", type: "GET",
success: function(data)
{
var data = data.split("-");
data.forEach(function(entry)
{
if (entry != "")
{
$("#check_status_" + entry).html('text');
}
});
}
});
}
variable entry is not empty, the problem is when I put it into the selector.
Thanks.
[update]
{
var test = "aaa-bbb-ccc";
var data = test.split("-");
data.forEach(function(entry) {
if (entry != ""){
$("#check_status_" + entry).html('!NEW!');
}
});
}
nothing the same
It seems to work fine if you are achieving something like this
data.forEach(function(entry) {
if (entry) {
$("#check_status_" + entry).html('text');
}
});
I have an ajax for retrieving names from the database, when the names are more than one, i split them then clone the first class so that i can have the other name(second) in the cloned class. It seems not to work, What am i missing?
$.ajax({
type: "POST",
url: base_url + "c_transfer/viewTransfer/" + transfer_id,
dataType: "json",
success: function (data) {
var all_transferors = data[0]['Transferor_Name'];
var sole_transferors = all_transferors.split(',');
for (transferor_counter = 0; transferor_counter < sole_transferors.length; transferor_counter++) {
if (transferor_counter > 0) {
$('.clone').relCopy({});
$("#transferor_name").val(sole_transferors[transferor_counter]);
} else {
$("#transferor_name").val(sole_transferors[transferor_counter]);
console.log(sole_transferors[transferor_counter]);
}
// console.log(sole_transferors[transferor_counter]);
}
Are you trying to do this?
$("#transferor_name").val(sole_transferors[transferor_counter].val());
You need to use .val() at the end?
I am using jQuery to insert an HTML shell into a page, and populate the shell with XML. Here is the XML in question
<minorPropCategory title="Test Title 1">
<minorProp>FLV</minorProp>
<minorProp>BLV</minorProp>
<minorProp>RLV</minorProp>
</minorPropCategory>
<minorPropCategory title="Test Title 2">
<minorProp>LAS</minorProp>
<minorProp>ILV</minorProp>
<minorProp>BIL</minorProp>
</minorPropCategory>
So first, what I do is import an HTML snippet for each minorPropCategory, and add the title using this code
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
Then, what I want to do is add another HTML snippet, and then populate it. This is where I am having a problem. I can try it like this
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
But it never shows up on the page, because I don't think it is firing at the proper time. Alternatively, I tried moving the creation of the minor modules into the .load function of it's parent, but I run into another problem. The code looks like this.
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
$(this).find('minorProp').each(function(){
alert("minorPropFired");
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
alert("test");
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
The problem is, that the line with "$(this).find('minorProp').each(function(){" doesn't fire because "this" has changed. I guess, by now, my noob is showing. I feel like I am doing this in the wrong way. Any help would be appreciated. Thanks.
Posted below is the full .js file of what I am trying to do.
// JavaScript Document<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
//gets the code for the ad from the URL. Using URL jQuery add-on to make this super-easy
var adCode = $.url.param("adCode");
if (adCode != null){
//gets the ad code's XML file
$.ajax({
type: "GET", url: adCode+".xml", dataType: "xml",
success: function(xml) {
//Set the header image
$("#headerImg").attr(
{
src:$(xml).find('headerImage').text(),
alt:$(xml).find('headerImageAlt').text()
}
);
//set the header text
$("#headerText").html($(xml).find('adText').text());
//set the top image
$("#topImg").attr(
{
src:$(xml).find('topImage').text(),
alt:$(xml).find('topImageAlt').text()
}
);
//MAJOR MODULE CODE - This code reads all of the major modules, then adds a majorModule div, and populates it
//Gets all majorProps from ad XML
$(xml).find('majorProp').each(function(){
var propCode=$(this).text();
var majorModuleCode = "majorModule.html";
//names the div with a unique ID
div = $("<div id='"+propCode+"majorModule' class='majorModule'>");
//Sets loading message in case it takes longer than usual to load
div.html("Loading......");
//After majorModule.html code loads, starts populating module
div.load(majorModuleCode,"t",
function(){
//Get the XML for the prop, which contains prop specific stuff
$.ajax({
type: "GET",
url: propCode+".xml",
dataType: "xml",
success: function(xml2) {
$("#"+propCode+"majorModule").find(".propImg").attr(
{
src:$(xml2).find('smallImage').text(),
alt:$(xml2).find('smallImageAlt').text()
}
);
$("#"+propCode+"majorModule").find(".propLogoImg").attr(
{
src:$(xml2).find('smallLogo').text(),
alt:$(xml2).find('name').text()
}
);
$("#"+propCode+"majorModule").find(".viewCalendarLinkA").attr(
{
href:"https://www.harrahs.com/AvailabilityCalendar.do?propCode="+propCode+"&showHotDeal=Y"
}
);
$("#"+propCode+"majorModule").find(".learnMoreLinkA").attr(
{
href:$(xml2).find('homeLink').text()
}
);
$("#"+propCode+"majorModule").find(".propText").html(
$(xml2).find('bodyText').text()
);
}
});
//Get the lowest rate for the prop
$.ajax({
type: "GET",
url: "lowest_rate\\"+propCode+".xml",
dataType: "xml",
success: function(xml3) {
$("#"+propCode+"majorModule").find(".roomRate").html(
"$"+($(xml3).find('roomtype').filter(
function (index) {
return $(this).attr("lowest") == "Y";
}).text()).slice(0, -3)
)
}
});
}
);
$("#mainModuleContainer").append(div);
});
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
}
});
}
});
To fix this problem just before running minorDiv.load do something like this
var elem = $(this);
minorDiv.load(minorModuleContainerCode,"t", function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").
html(minorHeader);
// replace $(this) with elem here
elem.find('minorProp').each(function(){
...
}
...
}
This will keep the reference to correct object in your nested functions.