Append Cells to Collection using Javascript - javascript

I currently am trying to simulate a mailbox and am using materialize in order to build it. Inside of my collection view, I am trying to add cells dynamically, but am unsure on how to proceed with appending html using Javascript.
<div class="row" id="mailBox">
<div class="container col s7">
<div class="collection-header center">
<h4>Email Box</h4>
</div>
<ul class="collection with-header" id="mailCollection">
<!-- Start: Trying to Dynamically Add These Cells To this view -->
<li class="collection-item avatar email-unread">
<span class="circle indigo darken-1"></span>
<span class="email-title"> Subject </span>
<p class="truncate grey-text ultra-small"> Message </p>
<span class="blue-text ultra-small">Date Recieved</span>
</li>
<!-- End of Cell Content -->
</ul>
</div>
</div>
I trying to append the collection items as such through my javascript, although nothing is appearing on the screen:
function createHTML(){
var jsonData = jsonObject;
for(var i =0; i < jsonData.length; i++){
$("#mailCollection").append('<li class="collection-item avatar email-unread">' +
'<span class="circle indigo darken-1"></span>'
'<span class="email-title">' + jsonData[0] + '</span>'
'<p class="truncate grey-text ultra-small">' + jsonData[1] + '</p>'
'<span class="blue-text ultra-small">' + jsonData[2] + '</span>
</li>')
}
}

As per your code, There are so many syntax errors in single and double quotes where you append the html. Please check below code without any syntax error.
function createHTML(){
var jsonData = jsonObject;
for(var i =0; i < jsonData.length; i++){
$("#mailCollection").append("<li class='collection-item avatar email-unread'><span class='circle indigo darken-1'></span><span class='email-title'>' + jsonData[0] + '</span><p class='truncate grey-text ultra-small'>' + jsonData[1] + '</p><a href='#!' class='secondary-content email-time'><span class='blue-text ultra-small'>' + jsonData[2] + '</span></a></li>")
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="mailBox">
<div class="container col s7">
<div class="collection-header center">
<h4>Email Box</h4>
</div>
<ul class="collection with-header" id="mailCollection">
<!-- Start: Trying to Dynamically Add These Cells To this view -->
<li class="collection-item avatar email-unread">
<span class="circle indigo darken-1"></span>
<span class="email-title"> Subject </span>
<p class="truncate grey-text ultra-small"> Message </p>
<span class="blue-text ultra-small">Date Recieved</span>
</li>
<!-- End of Cell Content -->
</ul>
</div>
</div>

Related

How i can do a modal with picture

I ask a question about my function Javascript.
I recover a data list after an a ajax call.
In the list i have a field with a picture and i want show this in a modal bootstrap.
In my code the picture is displayed below the column.
Thanks in advance guys :)
$.when(promiseListeRubriqueDocument).then(function(result) {
var data = JSON.parse(result);
$(".listRubrique").html("");
$.each(data, function(index, item) {
console.log(item);
var rubTemplate = $(".template");
var modal = (".img");
var rub = $(rubTemplate).clone().removeClass("template").removeClass("hide");
$(rub).find(".labelRubrique").text(item.codeRubrique);
$(rub).find(".inputRubrique").val(item.libelleRubrique);
$(rub).find("div.rubrique-image").attr("data-rubrique-id", item.idRub);
$(rub).find("div.rubrique-image[data-rubrique-id=" + item.idRub + "]").click(function(i, element) {
if (item.imageRubrique) {
if ($("" + "[data-rubrique-id=" + item.idRub + "]").find('img.rubrique-exemple').length < 1) {
$("" + "[data-rubrique-id=" + item.idRub + "]").append("<div><img class='rubrique-exemple' src=" + item.imageRubrique + " width='100px' /></div>");
}
}
});
$(".listRubrique").append(rub);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="list-group-item template hide">
<label class="labelRubrique" style="font-weight:bold"></label>
<div class="row rubrique-image" data-rubrique-id="">
<div class="col-md-8">
<input name="enteteRubrique" id="enteteRubrique" maxlength="255" type="text" class="form-control aveo-icon aveo-magnifier inputRubrique" disabled/>
</div>
<div class="col-md-3">
<a class="seeImage" href="javascript:void(0);" role='button' aria-expanded='false' aria-controls='collapseExample'><span class='glyphicon glyphicon-eye-open fa-lg'></span></a>
</div>
</div>
</li>
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<liferay-ui: messagekey="admin.gestion.documents.rubriques.disponibles" />
</div>
<div class="panel-body">
<ul class="list-group listRubrique">
</ul>
</div>
</div>
</div>
</div>
"Lightbox" is the common name for what you've described. Since you mentioned a modal bootstrap, something like http://jbutz.github.io/bootstrap-lightbox/ is likely to be aligned with your goals.
simply clone your "field" div, give it id then append to a bootstrap modal body. Or to avoid appending new clone everytime: use .html() instead.
from https://www.w3schools.com/bootstrap/bootstrap_modal.asp with modification, using bootstrap 3.3.7, jquery 3.3.1
<body>
<div class="container">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<div id='myColumn'>
<img src="https://via.placeholder.com/350x150"/>
<p>Some text in the modal.</p>
</div>
</div>
<script>
$(document).ready(function(){
// var field = $("" + "[data-rubrique-id=" + item.idRub + "]").clone();
var fieldtest= $('#myColumn').clone();
var modal = $("<div id='myModal' class='modal'>\
<div class='modal-dialog'>\
<div class='modal-content'>\
<div id='myBody' class='modal-body'>\
</div>\
</div>\
</div>\
</div>").appendTo('body');
// $('#myBody').html(field);
$('#myBody').html(fieldtest);
});
</script>
</body>
`

jquery each selector and ajax not producing the right results

I am trying to simplify my code but running into issues where it is not working when it place in an each loop.
Here is what I am trying to do:
- html has n parent DIV that generates a report via an AJAX call to pull data
- each div respective to report utilizes a data attribute to define which report to pull
- based no the results of the report, it should populate the html with the respective results.
HTML Code (to simplify, using n = 2):
<div class="widget-box widget-hits card no-border bg-white no-margin" data-widget-report="widget-hits">
<div class="container-xs-height full-height">
<div class="row-xs-height">
<div class="col-xs-height col-top">
<div class="card-header top-left top-right">
<div class="card-title text-black hint-text">
<span class="font-montserrat fs-11 all-caps">Weekly Hits
<i class="far fa-chevron-right p-l-5"></i>
</span>
</div>
<div class="card-controls">
<ul>
<li>
<a data-toggle="refresh" class="card-refresh text-black" href="#">
<i class="far fa-circle fa-xs"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row-xs-height ">
<div class="col-xs-height col-top relative">
<div class="row">
<div class="col-sm-6">
<div class="p-l-20 widget-total">
<h3 class="no-margin p-b-5"></h3>
<p class="small hint-text m-t-5">
<span class="label m-r-5">%</span>
</p>
</div>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="widget-chart"></div>
</div>
</div>
</div>
</div>
<div class="widget-box widget-sales card no-border bg-white no-margin" data-widget-report="widget-sales">
<div class="container-xs-height full-height">
<div class="row-xs-height">
<div class="col-xs-height col-top">
<div class="card-header top-left top-right">
<div class="card-title text-black hint-text">
<span class="font-montserrat fs-11 all-caps">Weekly Sales
<i class="far fa-chevron-right p-l-5"></i>
</span>
</div>
<div class="card-controls">
<ul>
<li>
<a data-toggle="refresh" class="card-refresh text-black" href="#">
<i class="far fa-circle fa-xs"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row-xs-height ">
<div class="col-xs-height col-top relative">
<div class="row">
<div class="col-sm-6">
<div class="p-l-20 widget-total">
<h3 class="no-margin p-b-5"></h3>
<p class="small hint-text m-t-5">
<span class="label m-r-5">%</span>
</p>
</div>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="widget-chart"></div>
</div>
</div>
</div>
</div>
JS:
$('.widget-box').each(function() {
$widget_report = $(this).data('widget-report');
if ($widget_report !== undefined) {
$.ajax({
type: 'get',
url: '/admin/reports/' + $widget_report,
dataType: 'json',
success:
function(data) {
if (data.success) {
var labelsData = [];
var seriesData = [];
var trend = data.trend * 100;
widget_class = '.' + $widget_report + ' .widget-chart';
console.log(widget_class);
$(this).find('.widget-total h3').text(data.total);
$(this).find('.widget-total p span').text(trend + '%');
trend_span = $(this).find('.widget-total p').children('span');
if(data.trend > 0) {
$(this).find('.widget-total p span.label').addClass('label-success');
$(this).find('.widget-total p').text('Higher');
}
else {
$(this).find('.widget-total p span.label').addClass('label-important');
$(this).find('.widget-total p').text('Lower');
}
$(this).find('.widget-total p').prepend(trend_span);
$.each(data.values, function(key, value){
date = new Date(value.label + 'T00:00:00');
labelsData.push(date.getMonth() + 1 + '/' + date.getDate());
seriesData.push(value.value);
});
chartData = {
labels: labelsData,
series: [seriesData]
}
alert(widget_class);
new Chartist.Bar(widget_class, chartData, {
axisX: {
showGrid: false
},
axisY: {
showGrid: false,
showLabel: false
}
});
}
}
});
}
});
Here are the problems I've encountered:
$(this).find('.widget-total h3').text is not updating the respective DIV group
widget_class for some reason is always returning the last DIV group... even if the last DIV group was returning data.success = false. Ex: above would return widget-sales twice and not widget-hits and then widget-sales.
I am scratching my head on this one... I am able to get this to work without the .each loop and distinctively create one for each... but was hoping to make this universal and allow the control rely on the data-widget-report attribute on the html.
Is this the proper approach?
Any help / direction is appreciated...
Add var in front of widget_class and $widget_report so they are scoped to the function instead of global. I think that will fix your problem. Right now $widget_report gets replaced by the last widget even before the ajax calls are completed.
As for the $(this) not working, you have to assign it to a variable before you make the ajax call.
$('.widget-box').each(function() {
var widgetBoxElement = $(this);
var $widget_report = $(this).data('widget-report');
if ($widget_report !== undefined) {
$.ajax({
type: 'get',
url: '/admin/reports/' + $widget_report,
dataType: 'json',
success:
function(data) {
if (data.success) {
// use widgetBoxElement here instead of $(this)
}
}
});
}
});

How to find the html after unwrap the div element using Jquery

I have following html code
<div class="main">
<div id="magicdomid2" class="">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class=""><br></div>
<div id="magicdomid4" class="">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class=""><br></div>
<div id="magicdomid6" class="">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>
Here is the html content
var html = $(".main").html();
I need to get the following htm in a variable
<div class="main">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
<br>
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
<br>
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
I tried following code
var text = $('div.main div').contents().unwrap().siblings('div').remove();
The variable "text" will get an object and i need the html content in a variable.. Please help me to find it.
Is their any possibility to export the customised html or xml format from etherpad ??
May it Help!
var htm = "";
$("div[id^='magicdomid']").each(function(i,val){
htm = htm + $(this).html();
});
$("div[class='main']").empty().html(htm);
//You can also use this for the same
$("div[id^='magicdomid']")
.contents()
.filter(function() {
return this.nodeType === 1;
})
.unwrap()
.end()
.filter(function() {
return this.nodeType === 3;
})
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="magicdomid2" class="">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class=""><br></div>
<div id="magicdomid4" class="">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class=""><br></div>
<div id="magicdomid6" class="">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>
unwrap and contents might not be the best to use in this case as they tend to modify the actual DOM tree rather than the html variable.
Try this:
// create empty div
var htmlContent = $('<div class="main"></div>');
// loop over magic class & append its content
$('.main .magic').each(function(i, n) {
htmlContent.append($(this).html());
});
// wrap & move one level above to get "main" div in html string
htmlString = htmlContent.wrap('<div></div>').parent().html();
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="magicdomid2" class="magic">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class="magic"><br></div>
<div id="magicdomid4" class="magic">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class="magic"><br></div>
<div id="magicdomid6" class="magic">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>

call Load more function for active tab

I'm trying to develop a load more function for a specific tab pane, in this case, the active tab pane. I'm having issues with this jquery function because I'm calling the load more in the end of all tabs, and in my JS function I can't figure out how to load after the pane that is active, in which the button was clicked. This way I keep loading the questions in the last pane, but I couldnt print without var lastItem = $('div.question-col .question-summary:last');
$(document).ready(function () {
$(".load-more").on('click', function (e) {
var tab = $(this).data('tab');
var next_page = $(this).data('next-page');
console.log(next_page);
console.log(tab);
$.get($(this).data('url') + '?tab=' + tab + '&page=' + next_page, function (data) {
addNewQuestions($.parseJSON(data));
});
$(this).data('next-page', parseInt(next_page) + 1);
});
siteStats();
});
function addNewQuestions(objects) {
$.each(objects, function (i, object) {
console.log(object);
var lastItem = $('div.question-col .question-summary:last');
var newLine = lastItem.clone(true);
var newObject = newLine.find('.question-info');
updateTitleAndLink(newObject.find('.summary a'), object);
updateCreationDate(newObject.find('.question-updated-at'), object);
updateQuestionAnswers(newObject.find('.question-answers'), object);
updateAnswerCount(newObject.find('.answers-count'), object);
updateViewsCount(newObject.find('.views-count'), object);
updateVotesCount(newObject.find('.votes-count'), object);
updateSolvedStatus(newObject.find('.status'), object)
lastItem.after(newLine);
});
}
The update functions are not relevant to this case, I guess.
<div id="tabs" class="tab-content">
<ul>
<li>Recent Questions</li>
<li>Unanswered Questions</li>
<li>Top Scored Questions</li>
</ul>
{if empty($recent_questions)}
<div class = "col-sm-12" style = "text-align: center"><strong>No questions to load!</strong></div>
{/if}
{if !empty($recent_questions)}
<div id="recent_questions" class="question-col">
<!-- Questions come here -->
<div class = "load-more"
data-next-page = "1"
data-url = "{url('controller/api/questions/load_more_questions')}"
data-tab = "recent_questions">
<a id="loadMore">
Load More...
</a>
</div>
</div>
{/if}
<div id="unanswered_questions">
<!-- Questions come here -->
<div class = "load-more"
data-next-page = "1"
data-url = "{url('controller/api/questions/load_more_questions')}"
data-tab = "unanswered_questions">
<a id="loadMore">
Load More...
</a>
</div>
</div>
<div id="top">
<!-- Questions come here -->
<div class = "load-more"
data-next-page = "1"
data-url = "{url('controller/api/questions/load_more_questions')}"
data-tab = "top_scored_questions">
<a id="loadMore">
Load More...
</a>
</div>
</div>
//Questions come here - Question template
<div class="question-summary narrow">
<div class="question-info col-md-12">
<div class="votes">
<div class="votes-count">
<span title="{$question['votes_count']} votes">
{if $question['votes_count']}
{$question['votes_count']}
{else}
0
{/if}
</span>
</div>
<div>votes</div>
</div>
<div {if $question['solved_date']}
class="status answered-accepted"
{else}
class="status answer-selected"
{/if}
title="one of the answers was accepted as the correct answer">
<div class="answers-count">
<span title="{$question['answers_count']} answer">{$question['answers_count']}</span></div>
<div>answer</div>
</div>
<div class="views">
<div class="views-count">
<span title="{$question['views_counter']} views">{$question['views_counter']}</span></div>
<div>views</div>
</div>
<div class="summary question-title">
<h3>
<a href="{questionUrl($question['publicationid'])}"
data-base-question-url = "{questionUrl('')}"
style="font-size: 15px; line-height: 1.4; margin-bottom: .5em;">
{$question['title']}
</a>
</h3>
</div>
<div class = "statistics col-sm-12 text-right" style="padding-top: 8px">
<span>
<i class = "glyphicon glyphicon-time"></i>
<span class="question-updated-at">{$question['creation_date']}</span>
</span>
<span>
<i class = "glyphicon glyphicon-comment"></i>
<span class="question-answers">{$question['answers_count']}</span>
</span>
</div>
</div>
</div>
My question is: is there any way to put my loaded content after the last item of the active pane?
Kind regards

Click on hidden element Selenium webdriver(javascript)

<tr id="mytr">
<td id="Table" onmouseover="this.className='menulevel1hl';" onmouseout="this.className='menulevel1norm'" class="menulevel1norm" onclick="PopupWin('Left',divMenu2011,this,'.menuitempopuprownormal','.menuitempopuprowhighlight','','.menuitempopupscroll' Alerts&nbsp </td>
<div id=" divMenu2011 " name="actiondiv " style="visibility:hidden;position:absolute;border: ">
<DIV myonclick="window.parent.location.href='/smcfs/console/exception.search' ; "> Alert Search</DIV>
</div>
<td id="Table " onmouseover="this.className='menulevel1hl' ; " onmouseout="this.className='menulevel1norm' " class="menulevel1norm " onclick="PopupWin( 'Left',divMenu2012,this, '.menuitempopuprownormal', '.menuitempopuprowhighlight', '', '.menuitempopupscroll'); "> Inventory </td>
<div id="divMenu2012 " name="actiondiv " style="visibility:hidden;position:absolute;border: ">
<DIV myonclick="window.parent.location.href='/smcfs/console/inventoryaudit.search' ; "> Inventory Audits</DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/inventory.detail?CurrentDetailViewID=YIMD080' ; "> Adjust Inventory</DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/itemsupsearch.search' ; "> Item Suppression Console</DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/additemsuppression.detail?CurrentDetailViewID=TGTOMSSCFD008' ; "> Add Item Suppression</DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/ProtectItem.detail?CurrentDetailViewID=TGTPID001' ; "> Add Protected Qty</DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/ProtectItem.search' ; "> Protected Qty Console </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/ProtectItemAudit.search' ; "> Protected Qty Audit Console </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/MCAFeeds.detail?CurrentDetailViewID=A001' ; "> Upload MCA Store Feed </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/MCAFeeds.detail?CurrentDetailViewID=A002' ; "> Upload MCA Item Feed </DIV>
</div>
<td id="Table " onmouseover="this.className='menulevel1hl' ; " onmouseout="this.className='menulevel1norm' " class="menulevel1norm " onclick="PopupWin( 'Left',divMenu2013,this, '.menuitempopuprownormal', '.menuitempopuprowhighlight', '', '.menuitempopupscroll'); "> RTAM Exclusion </td>
<div id="divMenu201404150720371518959 " name="actiondiv " style="visibility:hidden;position:absolute;border: ">
<DIV myonclick="window.parent.location.href='/smcfs/console/Exclusion.detail?CurrentDetailViewID=D002' ; "> RTAM Exclusion </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/Exclusion.detail?CurrentDetailViewID=001' ; "> Start RTAM Exclusion </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/Exclusion.detail?CurrentDetailViewID=D004' ; "> Remove Excluded Items </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/Exclusion.detail?CurrentDetailViewID=D003' ; "> Enter Exclusion Removal </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/Exclusion.detail?CurrentDetailViewID=D009' ; "> Schedule RTAMExclusion </DIV>
</div>
<td id="Table " onmouseover="this.className='menulevel1hl' ; " onmouseout="this.className='menulevel1norm' " class="menulevel1norm " onclick="PopupWin( 'Left',divMenu2014,this, '.menuitempopuprownormal', '.menuitempopuprowhighlight', '', '.menuitempopupscroll'); "> Sales Order </td>
<div id="divMenu2014 " name="actiondiv " style="visibility:hidden;position:absolute;border: ">
<DIV myonclick="window.parent.location.href='/smcfs/console/order.search' ; "> Sales Order Console </DIV>
<DIV myonclick="window.parent.location.href='/smcfs/console/shipment.search' ; "> Outbound Shipment Console</DIV>
</div>
I am trying to click on Ship Order Console. Please find the code below
WebElement ele1 = driver.findElement(By.xpath("//tr[#id='mytr']/td[4]"));
ele1.click();
WebElement ele = driver.findElement(By.xpath("//div[#id='divMenu2014']/div[1]"));
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript(js, ele);
System.out.println("element is " + ele.getText());
ele.click();
When I am printing the ele.gettext(), I am getting "sales order console", but when I am trying to click on it it is moving to inventory tab.
Could any one point out where it is going wrong?
Check this link to set attribute to web element,
How to use javascript to set attribute of selected web element using selenium Webdriver using java?
Alternatively, you can click using Javascript without making it visible. I have used CSS selector for your element.
executor.executeScript("$(\"div#divMenu2014>div\").click();");

Categories

Resources