I am trying to add data from a response inside a HTML block
What I have done
...
success: function () {
console.log($("#re-side-cart-items"))
$.getJSON('/cart.js', function (cart) {
$.each(cart.items, function (index, element) {
if(element.id == rewards_variant_id){
console.log($("#re-sidecart-item-template").html());
$("#re-side-cart-items").append($("#re-sidecart-item-template").html())
}
})
});
},
....
My HTML block was assigned to this var htmlwid = $("#re-sidecart-item-template").html();
<div id="re-sidecart-item-template" class="hide">
"<div class=cart-product row id=" + element.id + ">"
<div class="col-lg-3 col-md-3 col-sm-4 product-img">
<div class="image">
<div class="aspect-container">
<img src="element.img" alt="element.handle" loading="lazy" />
</div>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-7 product-info">
<div class="product-title">
element.title element.price/mo.</b>
</div>
</div>
</div>
</div>
I want to take the element values from the responses, it basically not working the way it should.
I was able to fix it
success: function () {
if (window.location.pathname == '/cart'){
window.location.href = "/cart";
}
else{
$.getJSON('/cart.js', function (cart) {
$.each(cart.items, function (index, element) {
if(element.id == rewards_variant_id){
$("#re-side-cart-items").append($('<div>').attr('id', element.id).attr('class', 'cart-product row')
.append($('<div>').attr('class', 'col-lg-3 col-md-3 col-sm-4 product-img')
.append($('<div>').attr('class', 'image')
.append($('<div>').attr('class', 'aspect-container')
.append($('<img>').attr('src', element.image).attr('alt', element.product_title).attr('loading', 'lazy')))))
.append($('<div>').attr('class', 'col-lg-8 col-md-8 col-sm-7 product-info')
.append($('<div>').attr('class', 'product-title')
.append($('<a>').attr('href', element.url)
.append(element.product_title + ' ' + element.price/100 + '/mo.')
)
.append($('<div>').attr('class', 'cart-pricing')
.append($('<a>').attr('href', '/cart/change?line='+element.index+'&quantity=0').attr('data-line', element.id)
.append('<u>Remove</u>')
))
))
);
}
})
});
}
},
Related
How can I use an boolean when my dataType is html? When my controller detects that there's no data on my sql, it should throw as false in my controller which is working, I just need to throw the boolean on my ajax as false. Im aware that using an html is automatically as true which is if I use an operator. It return as true. But how can I make it as false too?
Here's my controller:
if (Reader.HasRows == true)
{
return View("TrueViewPort");
} else
{
return View("FalseViewPort");
}
Ajax:
$.ajax({
url: "UrlToController",
type: "GET",
data: {
uname: uname
},
dataType: "html",
success: (function (result) {
if (result == true) { //even if its false, it always throw here
$('#wishlist-carousel').html(result); //if data detected carousel should be called
//Something elements when the data is true
} else {
//Something elements when the data is false
$(".no-page").html(result); //if no data. no carousel should detect
}
}),
error: (function (xhr, status) {
alert(status);
})
})
EDIT:
These should appear on my TrueViewPort:
#if (Model != null && Model.Rows.Count != 0)
{
#for (int i = 0, x = 1; i < Model.Rows.Count; i++, x++)
{
<div class="item">
<div class="text-center">
<div class="card">
<div class="card-img-top">
<img src="~/images/link/#Model.Rows[i][0]" />
</div>
<br />
<br />
<div class="card-body">
#Model.Rows[i][1]
<br />
#Model.Rows[i][2]
</div>
</div>
</div>
</div>
}
}
else //When the server detected that there's no data, it should throw the else statement which is working
{
<div class="container">
<div class="text-center">
<div class="not-found-404">
404
</div>
<br />
</div>
<div class="not-found">
ITEMS NOT FOUND
</div>
<br />
<div class="not-found-title">
Don't you have any want on the shop?
</div>
<br />
<div class="not-found-content">
Looks like you still haven't putting anything on your wishlist do you?
</div>
</div>
</div>
}
And here's what appear on my screen when launching it.
Using both if else operators to ==
Using if as == true and else
My .cshtml:
<div class="container">
<div class="text-center">
<div class="true">
<div class="card">
<div class="card-body">
<div class="owl-carousel owl-theme" id="wishlist-carousel"></div>
</div>
</div>
</div>
<div class="no-page"></div>
</div>
</div>
You could use your TrueViewPort as if else statement as you can see you given your TrueViewpor with 2 different <div>
Lets assume that you have any events on your javascript
$(document).ready(function() {
$.ajax({
success: function(result) {
$(".no-page").html(result); //if no data. no carousel should detect
$('#wishlist-carousel').html(result);
//Put here your owl function
}
})
})
Then change your .cshtml to:
<div class="container">
<div class="text-center">
<div class="true">
<div class="card">
<div class="card-body">
<div class="owl-carousel owl-theme" id="wishlist-carousel"></div>
</div>
</div>
</div>
</div>
</div>
<div class="no-page"></div> //separate these one, so if there's no data, the result will go here.
Then on your TrueViewPort:
#if (Model != null && Model.Rows.Count != 0)
{
#for (int i = 0, x = 1; i < Model.Rows.Count; i++, x++)
{
//add a <style> here to hide the no-page.
}
}
else
{
//add a <style> here to hide the owl carousel
}
You could just return one view and make the judement with the count of the target data in your target div
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "https://localhost:44332/Home/Partial",
success: function (result) {
var a = $("#test").children().length;
console.log(a);
if (a == 0) {
$(".no-page").html(result);
}
else {
$("#wishlist-carousel").html(result);
}
},
error: function (msg) {
console.log(msg);
}
})
return false;
});
</script>
<div class="container">
<div class="text-center">
<div class="true">
<div class="card">
<div class="card-body">
<div class="owl-carousel owl-theme" id="wishlist-carousel">
</div>
</div>
</div>
</div>
<div class="no-page"></div>
</div>
</div>
<div id="test">
<a>test</a>
</div>
Result1:
There's a "test" text in <div id="test"></div>
Delete the text:
I have a simple bootstrap page I need to load JSON data into it:
This is my script:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var tweets = JSON.parse(xhr.responseText);
var tweet = ' <div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">';
var name = ' <h4 class="card-title">';
var photo = ' <div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">';
for (var i = 0; i < tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
document.getElementById('photo').innerHTML = photo;
document.getElementById('name').innerHTML = name;
document.getElementById('tweet').innerHTML = tweet;
// close all html tags
}
}
};
xhr.open('GET', 'empdata.json');
xhr.send();
And this is my HTML:
<div class="container">
<div class="card">
<div class="card-header">
<div class="row">
<div id="photo">
<!-- here where the pic goes ! -->
</div>
<div id="name">
<!-- here where the name goes ! -->
</div>
</div>
<div class="card-block row">
<div id="tweet">
<!-- here where the tweet goes ! -->
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-block row">
<div id="tweet"> </div>
</div>
It loops correctly through all JSON data, but it displays all the pictures first then the names and finally the tweets separately. think the problem is related to the mechanism I follow in the loop.
I think you mean to do this. It can be much simpler but without changing your html I would do this:
var container = document.querySelector(".container");
for (var i=0; i<tweets.length; i += 1) {
var name = ' <h4 class="card-title">';
name += tweets[i].name;
name += '</h4> </div>';
var tweet = '<div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">'
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
var photo ='<div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">'
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
container.innerHTML+='<div class="card"><div class="card-header">'+
photo+name+tweet+'</div></div>';
}
EDITED Try set innerText outside from the loop
for (var i=0; i<tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
...
photo += tweets[i].pic;
photo += '"></div></div>';
}
document.getElementById('name').innerHTML = name;
document.getElementById('photo').innerHTML = photo;
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'some/url',
data: {
'name':'myname'
},
success: function (result) {
var result = ["student", "test"];
var length = result.length;
for (var i = 0; i < length; i++) {
var datastores = result;
$('#data_stores').append(
"<div class='col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore' id=" + datastores[i] + "> </div>");
}
}
})
var ids = $('#data_stores').children().map(function(){ return this.id }).get();
$('<pre>').appendTo('body').text(JSON.stringify(ids));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_stores">
</div>
<div id="data_stores">
<div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="students">
//Some other codes here
</div>
<div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="teachers">
//Some other codes here
</div>
</div>
This is a block of code in my HTML. The inner divs under data_stores are created using jquery. The IDs of the children div were result of an AJAX request and assigned on success.
The problem is, I need the ID values of the children divs to use for another AJAX call.
I ran the following:
console.log($("#data_stores"));
Output I got is the same above.
But for,
console.log($("#data_stores").find('.datastore'));
[prevObject: m.fn.init[1], context: document, selector: "#data_stores
.datstore"]
But, when accessing the child it says the element is undefined.
I need to do both AJAX calls on
$(document).ready(function() {
})
Using children like this works:
var ids = $('#data_stores').children().map(function(){ return this.id }).get();
var ids = $('#data_stores').children().map(function(){ return this.id }).get();
$('<pre>').appendTo('body').text(JSON.stringify(ids));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_stores">
<div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="students">
//Some other codes here
</div>
<div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="teachers">
//Some other codes here
</div>
</div>
I get Flickr gallery via API/Json. My issue with my code is that the gallery that I fetch has ~ 30 picture, but this snippet:
$.each(data.album.content,function (index,content)
{
album_container.append(column);
[...]
}
Appends only one <div> to the container, and not 30, but appends in right way 30 a/img to this unique column. I cannot figure why and how solve it.
Thank you for your help!
var album_container = $('div#album');
function callGetAjax(url)
{
return $.get(url,{});
}
function getAlbum(feed_url)
{
callGetAjax(absolute_path+'/feed/'+feed_url)
.success(function(data)
{
})
.error(function(xhr, statusText)
{//console.log(statusText);
})
.done(function(data)
{
var loaded = 0;
album_title = data.album.album_title;
$('h1#gallery-title').html(album_title);
var column = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>');
$.each(data.album.content,function (index,content)
{
album_container.append(column);
$('<a/>')
.append($('<img class="img-responsive">').prop('src', content.photo))
.prop('href', content.target)
.prop('title', content.title)
.attr('data-gallery', '')
.appendTo(column)
.colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});
});
});
}
Current HTML result:
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
<img src="..." />
<img src="..." />
<img src="..." />
[...]
</div>
HTML that I need:
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
<img src="..." />
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
<img src="..." />
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
<img src="..." />
</div>
[...]
Remember that .append() will move the HTML node around the DOM tree when the node already exists in your document. In your case, you have declared:
var column = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>')
…outside of your $.each() loop, therefore causing it to be repeatedly moved around inside album_container, instead of being cloned as you have expected. Therefore, what you would do is to declare it within your loop, such that the instance is not outside the scope of your loop:
var album_container = $('div#album');
function callGetAjax(url)
{
return $.get(url,{});
}
function getAlbum(feed_url)
{
callGetAjax(absolute_path+'/feed/'+feed_url)
.success(function(data)
{
})
.error(function(xhr, statusText)
{//console.log(statusText);
})
.done(function(data)
{
var loaded = 0;
album_title = data.album.album_title;
$('h1#gallery-title').html(album_title);
$.each(data.album.content,function (index,content)
{
// Creates a new column for every image element
var column = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>'),
item = $('<a/>')
.append($('<img class="img-responsive">').attr('src', content.photo))
.attr('href', content.target)
.attr('title', content.title)
.attr('data-gallery', '')
.appendTo(column)
.colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});
// Append column instance to the album container
album_container.append(column);
});
});
}
If you're also looking for a review of your code, may I suggest you transition away from the jqXHR.success() and jqXHR.error() methods? They have been deprecated in favour of the jqXHR.done() and jqXHR.fail() methods. Using promises, we have a backbone that looks like this:
var album_container = $('div#album');
function callGetAjax(url)
{
return $.get(url,{});
}
function getAlbum(feed_url)
{
// Store returned promise from $.get() in a variable
var ajaxCall = callGetAjax(absolute_path+'/feed/'+feed_url);
// Now we listen to the promise
ajaxCall
.done(function(data) {
var loaded = 0;
album_title = data.album.album_title;
$('h1#gallery-title').html(album_title);
$.each(data.album.content,function (index,content)
{
var column = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>'),
item = $('<a/>')
.append($('<img class="img-responsive">').attr('src', content.photo))
.attr({
'href': content.target,
'title': content.title,
'data-gallery': ''
})
.appendTo(column)
.colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});
album_container.append(column);
});
})
.fail(function(xhr, statusText) {
// Log error
// console.log(statusText);
});
}
Here is the code up to now. i want to access the value 1 of the <div class="field-item even">1</div>, and then if the value is 1 add a class, if the value is 0, add a another class. My code only access the first field-collection-container, i can't figure it out the problems.
$(document).ready(function () {
jQuery.each($('.field-collection-container'), function (i, obj) {
alert($(this).find('.field-items .content .field-item').text());
})
});
the html
<div class="container">
<div class="field-collection-container clearfix">
<div class="field field-name-field-interview-feeling field-type-field-collection field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items">
<div class="field-item even">
<div class="field-collection-view clearfix view-mode-full field-collection-view-final">
<div class="entity entity-field-collection-item field-collection-item-field-interview-feeling clearfix" about="/dtesthkinterview/field-collection/field-interview-feeling/4" typeof="">
<div class="content">
<div class="field field-name-field-19 field-type-list-boolean field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items">
<div class="field-item even">1</div>
</div>
</div>
<div class="field field-name-field-no-people field-type-list-boolean field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items"><div class="field-item even">0</div></div>
</div>
<div class="field field-name-field-untrust field-type-list-boolean field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items"><div class="field-item even">0</div></div>
</div>
<div class="field field-name-field-waste-money field-type-list-boolean field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items"><div class="field-item even">0</div></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="field-collection-container clearfix">
.....
</div>
<div class="field-collection-container clearfix">
.....
</div>
$('.field-collection-container .field-items .field-item').addClass(function () {
return $(this).text() === "1" ? "one-class" : "another-class";
});
Note that you do not need .each() at all.
You could use $.trim($(this).text()) if you expect spaces to be present.
jQuery.each($('.field-collection-container .field-items .content .field-item'), function (i, obj) {
if($(this).text() == "1"){
$(this).addClass("someclass");
}else if($(this).text() == "0"){
$(this).addClass("anotherClass");
}
});
Working Example http://jsfiddle.net/P9meu/
Check this sample on jsFiddle
http://jsfiddle.net/vijaypatel/Q2GHV/
$(function () {
$('.field-collection-container').each(function (index, obj) {
$(this).find('.field-items .content .field-item').each(function (index, obj) {
alert($(this).text());
if ($(this).text() == '1') {
$(this).prop('class','One');
} else {
$(this).prop('class','Zero');
}
});
});
});
Above code is woroking fine with multiple "field-collection-container" and also modify odd even elements
<div class="field-items">
<div class="field-item even">
<div class="field-collection-view clearfix view-mode-full field-collection-view-final">
<div class="entity entity-field-collection-item field-collection-item-field-interview-feeling clearfix" about="/dtesthkinterview/field-collection/field-interview-feeling/4" typeof="">
<div class="content">
<div class="field field-name-field-19 field-type-list-boolean field-label-above">
<div class="field-label">TEXT</div>
<div class="field-items">
<div ***id="id1"*** class="field-item even">1</div>
</div>
Instead of calling like this
$(document).ready(function () {
jQuery.each($('.field-collection-container'), function (i, obj) {
alert($(this).find('.field-items .content .field-item').text());
})
});
u can use id for a div and call like this
$(document).ready(function () {
{
var t=$("#id").text();
alert(t);
if(t==1)
{
$("#id1").addClass(".classname");
}
else
{
if(t==0)
{
$("#id1").addClass(".anotherclassname");
}
}
})
Please find the below code and i hope it solves your problem
$("div.content").find("div.field-item").each(function () {
if ($(this).html() == 1)
$(this).addClass("evenDivClass");
else if ($(this).html() == 0)
$(this).addClass("oddDivClass");
});
If you really only want the alternating fielditem divs in different classes you could try
$.each($(".field-item").find(".even"), function(i,o){ if(o.textContent==="1") $(o).addClass("some"); if(o.textContent==="0") $(o).addClass("other");)
Which is short and fast.
Here is an example of a javascript solution
var fieldItems = document.querySelectorAll(".field-collection-container .field-item");
Array.prototype.forEach.call(fieldItems, function (fieldItem) {
var text = fieldItem.textContent.trim();
if (text === "0") {
fieldItem.className += " Zero";
} else if (text === "1") {
fieldItem.className += " One";
}
});
On jsfiddle