Add class/text to a jQuery element - javascript

I'm trying to clone the following HTML template and add class/text to it.
<template id="result">
<section>
<div class="alert">
<p class="someText"></p>
</div>
</section>
</template>
So the user first submits a question:
<div id="answer"></div>
<section class="row">
<form id="form" action="/" method="GET">
<div>
<input id="question" />
</div>
</form>
</section>
Then the script executes:
$(document).ready(function () {
$('#form').on('submit', function (event) {
$.ajax({
data: {...},
type: 'GET',
url: '/result'
}).done(myFunction);
});
});
And finally it clones the template (ID #result), add a class to the element containing a class alert and add some text to the element containing a class someText, and appends it to the element containing ID #answer.
function myFunction(result) {
clone = $('#result').clone();
$('.alert', clone).addClass('myClass');
$('.someText', clone).text('myText');
clone.appendTo("#answer");
}
The function executes (I added a console.log() to the end of it to be sure) but nothing is appending.

Consider the following.
function create_message(result) {
var section = $("#result").children().clone();
$('.alert', section).addClass(result.status);
$('.address', section).text(result.address);
$('.extract', section).text(result.extract);
$('.question', section).text(result.question);
section.appendTo("#answer");
}
This creates a clone of all the HTML Elements inside the Template with ID result. It then finds specific classes inside the Object section and makes changes.
You can also do the following.
section.find(".alert").addClass(result.status);
See more: https://api.jquery.com/clone/
Update
Use <template> to hold some content that will be hidden...
So if you Clone the Template and append it, it will still be hidden.
Try the following:
function myFunction(result) {
clone = $('#result > section').clone();
$('.alert', clone).addClass('myClass');
$('.someText', clone).text('myText');
clone.appendTo("#answer");
}
Update 2
I don't use <template>, so I had to re-read some stuff. It has a content portion, so it has an HTML Fragment contained within and is not like other HTML Elements, more like an iFrame. So we need to collect the content versus cloning it.
See: How to use HTML template tag with jQuery?
Here is a working example: https://jsfiddle.net/Twisty/rpd9h0mf/20/
Your code will be something more like the following.
JavaScript
$(function() {
function showResults(results) {
var clone = $($('#result').html());
$('.alert', clone).addClass(results.class);
$('.someText', clone).text(results.answer);
clone.appendTo("#answer");
}
$('#question-form').submit(function(event) {
event.preventDefault();
$.ajax({
data: {
q: $("#question").val()
},
type: 'GET',
url: '/result',
success: showResults
});
});
});
This creates a new jQuery Object based on the HTML Content of the Template. Now you can properly edit it and append it.

Related

how can I create an html article for each element in a javascript array

i want to iterate a response and create an article section with each object
I have the following piece of code that makes the request:
$.ajax({
type: "POST",
url: "http://0.0.0.0:5001/api/v1/places_search/",
data: JSON.stringify({}),
dataType: 'json',
contentType: "application/json",
success: function (list_of_places) {
for (let place of list_of_places) {
$(".places").append("<article></article>");
// title box
$(".places article").append(`<div class="title_box">
<h2>${place['name']}</h2>
<div class="price_by_night">${place['price_by_night']}</div>
</div>`);
}
}
});
here's a snippet of the html to edit:
<section class="places">
<!-- <h1>Places</h1> -->
</section>
here's a screenshot of the result of the snippet:
How can I get only one object per article instead of all objects left in the iteration?
The issue is because within your for loop, $(".places article") is selecting all elements matching that selector in the DOM, so you repeatedly append the new items to each one.
To fix this you can append() the content to the article you just created:
for (let place of list_of_places) {
const $article = $('<article />').appendTo('.places');
$article.append(`<div class="title_box"><h2>${place.name}</h2><div class="price_by_night">${place.price_by_night}</div></div>`);
}
Alternatively you can use map() instead of your for loop to create an array of HTML strings which you append to the DOM as a whole:
const html = list_of_places.map(place => `<article><div class="title_box"><h2>${place.name}</h2><div class="price_by_night">${place.price_by_night}</div></div></article>`);
$('.places').append(html);
Try
$(".places article").eq(-1).append(`<div class="title_box">...
based on this answer to How do I select a single element in jQuery? in conjunction looking up eq in jQuery docs.

How do I replace variables in HTML with an object of variables from jQuery?

I am trying to make a system for my web page that gets the content of a template found in the HTML and then replaces the appropriate variables with the corresponding values which is stored in an object. The problem is that nothing is being replaced. In this example, I am getting the contents of an RSS file that displays forum posts. I use ajax to get the contents, then iterate through each item. I assign the xml tag values to an object whose keys correspond to the variabls in the HTML template. For every post found, it should replace the HTML variable with the contents of the xml tag.
This is my Javascript:
$.ajax({
url: "rsstest.xml",
type: "GET",
dataType: 'xml',
crossDomain: true,
success: function(xml){
var news = $('#news-results');
news.empty();
if($(xml).find('item').length > 0){
$(xml).find('item').each(function(){
var temp_vars = {
news_title: $(this).find('title').text(),
news_body: $(this).find('description').text(),
news_date: $(this).find('pubDate').text(),
news_link: $(this).find('link').text()
}
var template = $('#news-template').contents().clone();
for(const variable in temp_vars){
template.text().replace("{"+variable+"}", temp_vars[variable])
}
news.append(template);
})
} else {
news.append($('<p></p>').text('There is no news to display at this time.'));
}
}
})
This is my HTML:
<h1>Announcements</h1>
<div id="news-results">
</div>
<div id="news-template" style="display: none;">
<div class="media">
<div class="media-body">
<h3>{news_title}</h3>
<p>{news_body}</p>
<div class="media-footer">
<div class="col-left">
<h4>Posted on {news_date}</h4>
</div>
<div class="col-right">
Read More
</div>
</div>
</div>
</div>
</div>
What am I doing wrong?
Code below will only replace the text without assigning it.
template.html().replace("{"+variable+"}", temp_vars[variable])
You have to assign after replacing the text to update the actual value.
template.html(template.html().replace("{"+variable+"}", temp_vars[variable]))

jQuery - on load of element with ajax

I searched for some time but could not find a working solution for my problem (sorry if I searched wrongly)...
I would like to have the equivalent of the following function for an element loaded with ajax:
$(document).ready(function() {
$('.div-modal-text').css("background-color","red");
});
Therefore I am using the following code:
$('#parent_id').on('action', '#id or class to be born', function to be performed() );
In my example the parent-child structure is: #projectModals (div whose content is dynamically loaded)>...>.div-project-description>.div-modal-text
This translates into the following code in my example:
$('#projectModals').on('load', '.div-project-description', function() {
$(this).find('.div-modal-text').each(function() {
$(this).css("background-color","red");
});
});
I know 'load' does not work with .on(), but I tried different alternatives and I could not find anything working.
Thanks for your help!
EDIT: Here is my (simplified) HTML code:
<div id="projectModals"></div>
content loaded in #projectModals with Ajax:
<div class="row">
<div class="div-project-idcard">
column 1, don't bother too much about this column
</div>
<div class="div-project-description">
<div id="summary" class="div-modal-text">
Column2, text 1
</div>
<div id="purpose" class="div-modal-text"">
Column2, text 2
</div>
<div id="reforestation" class="div-modal-text">
Column2, text 3
</div>
<div id="certification" class="div-modal-text">
Column2, text 4
</div>
</div>
</div>
If you're waiting for it to be loaded via ajax, consider using $(window).ajaxSuccess() instead:
$(window).ajaxSuccess(function(){
$('#projectModals .div-project-description .div-modal-text').each(function() {
$(this).css("background-color","red");
});
});
for what I understand, you want to change some background color after an ajax has been executed.
I think it's best to make the operation in the ajax success
$.ajax({
url: "some url",
data: {some data},
success: onAjaxSuccess,
});
and then;
function onAjaxSuccess(data){
//.. do things with data
var toExecute = $('#projectModals .div-project-description');
toExecute.find('.div-modal-text').each(function() {
$(this).css("background-color","red");
});
}

render view model on item click

The situation is as follows: I have a Product model which has many properties and one is a List of Photo objects, each Photo object having an ID and a Name. There is a Carousel View having a model a list of Photos. In Product View I have something like this:
#if (Model.Photos.Count > 0)
{
....
<a href="javascript:jsFunction()".......
Where in javascript,the jsFunction looks like this:
function jsFunction()
{
alert('#Html.Action("GetPhotosCarousel", Model.Photos)');
}
and the Controller function returns the partial view _PhotosCarousel.
Now, the problem that #Html.Action executes on rendering the main view, NOT ON CLICK.
How can I render the view PhotosCarousel just on click and not on displaying the page?
I would suggest removing the actual call to jsFunction from your href and then handling it with jQuery.
Click Me
$(document).ready(function(){
$("#photoCarouselHref").click(function(){
$.ajax({
url: '#Url.Action("GetPhotosCarousel"),
//other ajax settings here
});
});
});
jQuery ajax documentation here.
You can try this:
the code is ready to have multiple anchor elements:
HTML:
<div class="container">
<a href="#Url.Action("GetPhotosCarousel")"
data-id="#Model.Id"
data-name="#Model.Name"
class="call-get-photos-carousel">click</a>
<div class="result"></div>
</div>
JS:
$(document).ready(function(){
$('.call-get-photos-carousel').bind('click', function(event) {
var
_this = this,
data = {'Id': $(this).data('id'), 'Name': $(this).data('name')};
$.get($(this).attr('href'), data, function(html) {
$(_this).siblings('.result').html(html);
});
return false;
});
});
but if you only have an anchor element, you can work in this way with ID in the element:
HTML:
<div>
<a href="#Url.Action("GetPhotosCarousel")"
data-id="#Model.Id"
data-name="#Model.Name"
id="call-get-photos-carousel">click</a>
<div id="result"></div>
</div>
JS:
$(document).ready(function(){
$('#call-get-photos-carousel').bind('click', function(event) {
var
_this = this,
data = {'Id': $(this).data('id'), 'Name': $(this).data('name')};
$.get($(this).attr('href'), data, function(html) {
$('#result').html(html);
});
return false;
});
});
in both cases the action is sent to the values ​​for the Id and Name.

How do you apply an item, from a list of results, to the parent Div tag for the current object?

I am trying to build a function for inserting the number of Facebook Likes into a Div tag. So far, I have a script that can get the URL from a Div tag which is inside of another Div tag called 'entry' and then have the .getJSON() method retrieve the number of Facebook likes for each entry.However, I can't get each retrieved value of Facebook Likes to insert into a Div tag for each entry. Please note, I simplified my code to where it alerts each Facebook Like value. This is what I have so far:
<div class="entry">
<div class="fburl">https://graph.facebook.com/zombies</div>
<div class="facebook-likes"></div>
</div>
<div class="entry">
<div class="fburl">https://graph.facebook.com/starwars</div>
<div class="facebook-likes"></div>
</div>
And here's my jQuery:
$(document).ready(function(){
$(".entry").each(function() {
var fbURL = $(this).find(".fburl").html();
$.getJSON(fbURL, function(fbData) {
var fbArr = fbData['likes'];
alert(fbArr);
});
});
});
​So what I am trying to do is iterate through each entry, get the Open Graph URL for it, retrieve the Likes value, and then insert it into the appropriate Div tag, so the code should render as:
<div class="entry">
<div class="fburl">https://graph.facebook.com/zombies</div>
<div class="facebook-likes">2,586 Likes</div>
</div>
<div class="entry">
<div class="fburl">https://graph.facebook.com/starwars</div>
<div class="facebook-likes">8,905,721 Likes</div>
</div>
​
​
$(document).ready(function() {
$('.entry').each(function() {
var $this = $(this),
fbURL = $this.children('.fburl').html();
$.getJSON(fbURL, function(fbData) {
$this.children('.facebook-likes').html(fbData['likes'] + ' Likes')
});
});
});
See: http://api.jquery.com/children
Demo: http://jsfiddle.net/9EALz/2/
Note: Using children() is going to be marginally more efficient than using find() as it limits the DOM traversal to a single level ( http://jsperf.com/find-vs-children/13 ). Cashing the jQuery object $(this) via var $this = $(this) is also slightly more efficient as it prevents unnecessary selector interpretation ( http://jsperf.com/jquery-cache-vs-no-chace ).
You may want this
$(document).ready(function(){
$(".entry").each(function() {
var entry=$(this), fbURL=$(".fburl", entry).html(),
el=$('.facebook-likes', entry);
$.getJSON(fbURL, function(fbData) {
el.html(numberWithCommas(fbData['likes'])+" Likes");
});
});
});​
A thousand separator function from here
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
DEMO.
Update:
Alternatively you can use this too (using data-attribute) without an extra div for fburl, i.e.
<div class="entry">
<div data-fburl="https://graph.facebook.com/zombies" class="facebook-likes"></div>
</div>
JS
$(".entry").each(function() {
var entry=$(this), fbURL = $(".facebook-likes", entry).attr('data-fburl'),
el=$('.facebook-likes', entry);
$.getJSON(fbURL, function(fbData) {
el.html(numberWithCommas(fbData['likes'])+" Likes");
});
});

Categories

Resources