jquery append() is creating two div elements - javascript

I am adding div elements dynamically to the DOM using jquery append(). I have made a controller that takes json data using $http.get() and calls a function create_mission to add the divs to DOM. I have to create a div for every object of the json, so i have done it using a loop and iterating it for json.length times. But here two div elements gets created at every iteration.
Here is my controller
mission_vision_mod.controller('mission_visionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.visiontext = "Here is the content of vision";
$scope.bkclr = ['bk-clr-one', 'bk-clr-two', 'bk-clr-three', 'bk-clr-four'];
$scope.progressbar = ['progress-bar-warning', 'progress-bar-danger', 'progress-bar-success', 'progress-bar-primary'];
$scope.missioncount = ['col-md-0', 'col-md-12', 'col-md-6', 'col-md-4', 'col-md-3', 'col-md-2.5', 'col-md-2'];
$http.get('m_id.json').success(function (data) {
$scope.missions = data;
$scope.len = data.length;
create_mission();
});
var create_mission = function () {
var i;
for (i = 0; i < $scope.missions.length; i++) {
$("#missionstart").append("<div id='" + $scope.missions[i].id + "' class='" + $scope.missioncount[$scope.missions.length] + "'></div>");
$("#missionstart").find("#" + $scope.missions[i].id + "").append("<div class='dashboard-div-wrapper " + $scope.bkclr[i] + "'></div>");
$("div#" + $scope.missions[i].id + "").find(".dashboard-div-wrapper").append("<h1>" + $scope.missions[0].missionInfo + "</h1>");
$("div#" + $scope.missions[i].id + "").find(".dashboard-div-wrapper").append("<div class='progress progress-striped active'></div>");
$("div#" + $scope.missions[i].id + "").find(".dashboard-div-wrapper").find("div").append("<div class='progress-bar " + $scope.progressbar[i] + "' role='progressbar' aria-valuenow='80' aria-valuemin='0' aria-valuemax='100' style='width: 80%'></div>");
$("div#" + $scope.missions[i].id + "").find(".dashboard-div-wrapper").append("<ul class='unorderedlist'></ul>");
}
}
}]);
The HTML file
<div class="content-wrapper" ng-controller="mission_visionCtrl">
<div class="container-fluid">
<div id="header-wrapper" class="container">
<div id="header" class="container">
<div id="logo">
<h1 class="page-head-line" id="visionh"><a>Vision</a></h1>
<p id="visionp"><a rel="nofollow">{{visiontext}}</a></p>
</div>
</div>
</div>
<div class="row" id="missionstart">
</div>
</div>
The json file
[{"id":1,"missionInfo":"mission"},{"id":2,"missionInfo":"mission1"},{"id":3,"missionInfo":"mission2"},{"id":4,"missionInfo":"mission3"}]

Since you have used angularjs, use a angularjs solution
<div class="content-wrapper" ng-controller="mission_visionCtrl">
<div class="container-fluid">
<div id="header-wrapper" class="container">
<div id="header" class="container">
<div id="logo">
<h1 class="page-head-line" id="visionh"><a>Vision</a></h1>
<p id="visionp"><a rel="nofollow">{{visiontext}}</a></p>
</div>
</div>
</div>
<div class="row" id="missionstart">
<div id="{{mission.id}}" ng-class="missioncount[missions.length]" ng-repeat="mission in missions">
<div class="dashboard-div-wrapper" ng-class="bkclr[$index]">
<h1>{{mission.missionInfo}}</h1>
<div class="progress progress-striped active">
<div class="progress-bar" ng-class="progressbar[$index]" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"></div>
</div>
<ul class="unorderedlist"></ul>
</div>
</div>
</div>
</div>
</div>
then
mission_vision_mod.controller('mission_visionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.visiontext = "Here is the content of vision";
$scope.bkclr = ['bk-clr-one', 'bk-clr-two', 'bk-clr-three', 'bk-clr-four'];
$scope.progressbar = ['progress-bar-warning', 'progress-bar-danger', 'progress-bar-success', 'progress-bar-primary'];
$scope.missioncount = ['col-md-0', 'col-md-12', 'col-md-6', 'col-md-4', 'col-md-3', 'col-md-2.5', 'col-md-2'];
$http.get('m_id.json').success(function (data) {
$scope.missions = data;
$scope.len = data.length;
});
$scope.missions = data;
$scope.len = data.length;
}]);

Firstly, I found a possible typo in your javascript code.
$("div#" + $scope.missions[i].id + "").find(".dashboard-div-wrapper").append("<h1>" + $scope.missions[0].missionInfo + "</h1>");
I believe what you want is $scope.missions[i].missionInfo. Other than this, your code should be fine.
Secondly, in angular world, the normal way to iterate is to use ng-repeat (please see Arun's answer). Your view and controller shouldn't know each other, and they should communicate through your model.

Inside Loop try this code:
var div2=$("div></div>").addClass("dashboard-div-wrapper "+$scope.bkclr[i]);
div2.append("<h1>" + $scope.missions[0].missionInfo + "</h1>");
div2.append($("<div></div>").addClass("progress progress-striped active").append("<div class='progress-bar " + $scope.progressbar[i] + "' role='progressbar' aria-valuenow='80' aria-valuemin='0' aria-valuemax='100' style='width: 80%'></div>"));
div2.find(".dashboard-div-wrapper").append("<ul class='unorderedlist'></ul>");
var div1=$("<div></div>").id($scope.missions[i].id).addClass($scope.missioncount[$scope.missions.length]).append(div2);
$("#missionstart").append(div1);
Code not tested. Test it and let me know.

Related

How to create if statement inside embedded HTML in JavaScript to show CSS class

How to display one of two classes based on if there is data in the js array.
e.g. if there is responseData.title show class grey else class white
I am trying this now:
let resultHTML = '<article class="item">\
<div class="post-main">\
<header class="clear">\
<a href="' + responseData.url + '"</a>\
<span class="post-date">just now</span>\
</header>\
'if (responseData.title) {
'<section class="grey">'
} else {
'<section class="white">'
}'\
' + articleImage + '\
<h3>' + responseData.title + '</h3>\
<div class="post-about">' + responseData.about + '</div>\
</section>\
</div>\
</article>';
You can use the ternary operator.
In your case, it would be like this:
let resultHTML = '<article class="item">\
<div class="post-main">\
<header class="clear">\
<a href="' + responseData.url + '"</a>\
<span class="post-date">just now</span>\
</header>\
' + responseData.title ?
'<section class="grey">'
:
'<section class="white">'
+ '\
' + articleImage + '\
<h3>' + responseData.title + '</h3>\
<div class="post-about">' + responseData.about + '</div>\
</section>\
</div>\
</article>';
I will prefer using Template literals (Template strings) with Conditional (ternary) operator which is more cleaner.
Demo:
let responseData = {title:'abc'}
let articleImage = 'test';
let resultHTML = `<article class="item">
<div class="post-main">
<header class="clear">
<a href=responseData.url </a>
<span class="post-date">just now</span>
</header>
${
responseData.title ?
'<section class="grey">'
: '<section class="white">'
}
${articleImage}
<h3> ${responseData.title} </h3>
<div class="post-about"> ${responseData.about} </div>
</section>
</div>
</article>`;
console.log(resultHTML);

Displaying appropriate error message when data from JSON doesn't get fetched in HTML

I've a sample JSON:
[
{
"componentid": 4,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "theme",
"shortdesc": "to set theme for different applications"
},
{
"componentid": 7,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "preferences",
"shortdesc": "preferences screen for apps"
}
]
I've a JavaScript code that goes through above JSON and fetches the data
function prepareTopComponentList(data) {
try {
var preparedHtml = "";
for (var count = 0; count < data.length; count++) {
preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
" <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
" <img class=\"img-fluid\" src=\"";
preparedHtml += data[count].displayImageUrl;
preparedHtml += "\" alt=\"N/A\">\n" +
" <div class=\"card-body\">\n" +
" <h4 class=\"card-title\">";
preparedHtml += data[count].title;
preparedHtml += "</h4>\n" +
" <p class=\"card-text\">";
preparedHtml += data[count].shortdesc;
preparedHtml += "</p>\n" +
" <a onclick='Redirect(this)' href='#' class=\"btn btn-info\" id=\"";
preparedHtml += "component_desc_=" + data[count].componentid;
preparedHtml += "\">Learn more</a>\n" +
" </div>\n" +
"\n" +
" </div>\n" +
" </div>";
}
$("#div_top_component").append(preparedHtml);
} catch (err) {
}
}
function Redirect(element) {
try {
window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
} catch (err) {
}
}
I also have a HTML code for displaying error:
<!--Error/Warning Modal-->
<div class="modal fade" id="modal_show_error" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="modal_error_title"></h4>
</div>
<div class="modal-body">
<p id="modal_error_description"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>
</div>
</div>
</div>
</div>
I'm fetching componentid from JSON. But if it is NULL, then I want a bootstrap error pop up saying that componentid is NULL. Catch block of above JavaScript code is empty, I'm not getting what code I should put there to get bootstrap error pop up.
If you want no string to be appened at all if one of the items is invalid, you can use the following (I did it in es6, but you get the id)
If you want only the valid items to be appened, you can just replace the throw statement by return memo;
try {
const preparedHtml = data.reduce((memo, item) => {
if(typeof(item.componentid) === typeof(null))
throw new Error(`All items must have a componentid`);
const htmlChunk = `<div class="col-lg-4" style="margin-top: 20px">\n
<div class="col-lg-4" style="margin-top: 20px">\n
<div class="card wow fadeIn" data-wow-delay="0.2s">\n
<img class="img-fluid" src="${item.displayImageUrl} alt="N/A">\n
<div class="card-body">\n
<h4 class="card-title">${item.title}</h4>\n
<p class="card-text">${item.shortdesc}</p>\n
<a onclick='Redirect(this)'
href='#' class=\"btn btn-info\" id=\""
component_desc_="${item.componentid}">Learn more</a>\n
</div>\n\n
</div>\n
</div>`;
return memo.concat(htmlChunk);
}, '');
$('#div_top_component').append(preparedHtml);
} catch (err) {
//bootstrap modal code
}
The === is used to check the quality of the value and the type of variable....
You can do something like this...
if(data[count].componentid === undefined || data[count].componentid === null){
//Use your modal code
}
else{
//preparedHTML code
}

Event firing twice in kendo collapsible

I have an app the uses the Progress JSDO to load data and, using the foreach method of the jsdo, append the data to three different lists in kendo collapsible panels depending on the status of one of the fields. For some reason, the lists are being appended twice in the code and I can't figure out why. I would appreciate another set of eyes on my code to help me get to the bottom of this mystery.
Here is the controller for the view (this is all wrapped in an IIFE with some other code, but this is the relevant section.):
app.scanBarcode = {
viewModel: new ScanViewModel(),
onShow: function () {
app.JSDOSession.addCatalog(app.JSDOSettings.catalogURIs);
app.locJSDO.fill();
$("#list-button").unbind().click(function () {
app.goToScanFail();
});
app.scanBarcode.getCurrentReport();
},
onHide: function () {
var reportJSDO = app.reportJSDO,
writeOutReport = app.scanBarcode.writeOutReport;
reportJSDO.unsubscribe('afterFill', writeOutReport);
},
getCurrentReport: function () {
var reportJSDO = app.reportJSDO,
writeOutReport = app.scanBarcode.writeOutReport;
//Fill the JSDO from db and call function to display the data
reportJSDO.subscribe('afterFill', writeOutReport);
reportJSDO.fill();
},
writeOutReport: function (jsdo, success, request) {
var date = app.getDate();
jsdo.foreach(function (report) {
var reportDate = report.data.STAMP_DT,
completed = "<span class='glyphicon glyphicon-ok'></span>",
notCompleted = "",
span;
if (reportDate == date) {
if (report.data.STAMP_TM == null) {
span = notCompleted;
$("#uncompleted-list").append(
"<li class='list-group-item'>" +
span + " " +
report.data.LOCATION_ID +
' ' +
report.data.LOCATION_NAME +
"</li>"
);
} else {
span = completed;
$("#completed-list").append(
"<li class='list-group-item'>" +
span + " " +
report.data.LOCATION_ID +
' ' +
report.data.LOCATION_NAME +
"</li>"
);
}
$("#all-list").append(
"<li class='list-group-item'>" +
span + " " +
report.data.LOCATION_ID +
' ' +
report.data.LOCATION_NAME +
"</li>"
);
}
});
}
}
This is the html for my view:
<div data-role="view" data-title="Scan Location" data-reload="true" data-layout="views-layout" data-model="app.scanBarcode.viewModel" data-show="app.scanBarcode.onShow" data-hide="app.scanBarcode.onHide">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<h3 class="hassubtitle">Begin Scan:</h3>
<button class="btn btn-xlg btn-primary btn-block" data-bind="click: scan">Scan</button>
<button id="list-button" class="btn btn-lg btn-default btn-block">Skip</button>
</div>
<div class="col-xs-12 col-md-6 col-md-offset-3">
<div data-role="collapsible" id="completed-collapsible">
<h2>
Completed
</h2>
<div data-role="scroller" id="completed-list"></div>
</div>
<div data-role="collapsible" id="uncompleted-collapsible">
<h2>
Uncompleted
</h2>
<div data-role="scroller" id="uncompleted-list"></div>
</div>
<div data-role="collapsible" id="all-collapsible">
<h2>
All
</h2>
<div data-role="scroller" id="all-list"></div>
</div>
</div>
I'm the only web developer at my work and I have no one to ask here, so I really appreciate you all!

How to append loop values in different div

I need append values different div-s
var thmb_count = thmb_wrap.length;
for( i = 0; i < thmb_count; i++){
var num = i + 1;
thmb_wrap.each(function(){
$(this).append('<span class="numeric">' + num + '/' + (full) + '</span>');
});
}
html
<div class="thumb-wrp scrollbar-inner">
<div class="thm-img"><img src="img/img/a.jpg"></div>
<div class="thm-img"><img src="img/img/b.jpg"></div>
<div class="thm-img"><img src="img/img/c.jpg"></div>
<div class="thm-img"><img src="img/img/d.jpg"></div>
<div class="thm-img"><img src="img/img/a.jpg"></div>
<div class="thm-img"><img src="img/img/c.jpg"></div>
<div class="thm-img"><img src="img/img/b.jpg"></div>
<div class="thm-img"><img src="img/img/d.jpg"></div>
</div>
You can iterate over the thm-img and append the span's like
var $thumbs = $('.thumb-wrp .thm-img'),
full = $thumbs.length;
$thumbs.append(function(i) {
return '<span class="numeric">' + (i + 1) + '/' + (full) + '</span>'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thumb-wrp scrollbar-inner">
<div class="thm-img"><img src="img/img/a.jpg"></div>
<div class="thm-img"><img src="img/img/b.jpg"></div>
<div class="thm-img"><img src="img/img/c.jpg"></div>
<div class="thm-img"><img src="img/img/d.jpg"></div>
<div class="thm-img"><img src="img/img/a.jpg"></div>
<div class="thm-img"><img src="img/img/c.jpg"></div>
<div class="thm-img"><img src="img/img/b.jpg"></div>
<div class="thm-img"><img src="img/img/d.jpg"></div>
</div>

How can I group divs and calculate values?

I have the next structure:
<div class="container">
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">111</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">222</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">333</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">444</div>
</div>
<div class="block">
<div class="id">2</div>
<div class="date">05/17/2015</div>
<div class="value">555</div>
</div>
</div>
I need group it and calculate values, then I need print this in my page.
Steps:
Group by ID
Group by Date (in ID)
Calculate Values (in each Date)
So, the result:
<div class="container">
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">333</div> <!-- 111+222 -->
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">777</div> <!-- 333+444 -->
</div>
<div class="block">
<div class="id">2</div>
<div class="date">05/17/2015</div>
<div class="value">555</div>
</div>
</div>
P.S. Of course, I don't need in comments. :)
Can you help me with JS/jQ code?
This is one way (demo):
var $container = $('.container'),
$blocks = $container.find('.block'),
results = {},
output = '';
$blocks.each(function () {
var $this = $(this),
id = $this.find('.id').html(),
date = $this.find('.date').html(),
value = $this.find('.value').html();
results[id] = results[id] || {};
results[id][date] = results[id][date] || 0;
results[id][date] += parseInt(value);
});
$.each(results, function (id, dates) {
$.each(dates, function (date, value) {
output += '<div class="block">' +
'<div class="id">' + id + '</div>' +
'<div class="date">' + date + '</div>' +
'<div class="value">' + value + '</div>' +
'</div>';
});
});
$container.html(output);

Categories