Unable to append modal using JavaScript - javascript

I'm unable to append a certain div to a modal when pulling in data using pnp and JavaScript.
The whole process explained:
Function DomyApiCalls - WORKS (Pulls in all the boxes with the titles)
Function filtering - WORKS (Filters the names in alphabetical order)
Function getModal - Doesn't work (I want it when a user clicks on a box, that the modal shows and just appends all the filesHtml to the .Modalbody class.
This is pulling in the page title, I need the folderName from below instead.
$(document).ready(function(){
DoMyApiCalls("boxWrap");
var current_title = $(document).attr('title'); //CURRENT_TITLE is supposed to be the "FolderName".
if(current_title == 'Acuvue') {
getModal("Acuvue");
}
});
function DoMyApiCalls(elementId) {
$.ajax({
url: "/bdm/business-development/_api/web/lists/GetByTitle('CompletedSubmissionTiles')/Items?$select=EncodedAbsUrl,Title,Line1,Line2,Hyperlink,TargetWindow,DescriptionHTMLOption,Line1,TileOrder&$orderby=Title asc",
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: function (data) {
if (data.d.results) {
var object = data.d.results;
var Line1var;
for(var i = 0; i < object.length; i++)
{
if(object[i].Line1 != null) { // Covers 'undefined' as well
Line1var = "<div class='Line1'>" + object[i].Line1 + "</div>";
} else {
Line1var = "";
}
$('#' + elementId).append("<div class='col-md-4 box' data-toggle='modal' data-target='#modal"+object[i].TileOrder+"' id='TileBox"+object[i].TileOrder+"'><div id='titleBox' class='titleBox'><h1>" + object[i].Title + "</h1><div style='width:250px; height: 130px;background-color: white; border: 1px solid lightgrey;'><img style='width: auto; height: inherit; margin-left: auto; margin-right: auto; display: block;' src='" + object[i].EncodedAbsUrl + "' alt='" + object[i].Title +"'/></div></div></div>");
filtering(object[i].Title);
}
}
}
});
};
function filtering(title) {
var filter = "Name eq '" + title + "'";
$pnp.setup({
baseUrl: "/bdm/business-development/"
});
$pnp.sp.web.folders.getByName('Completed Submissions').folders.filter(filter).expand("Files").get().then(function(data){
});
}
function getModal(folderName) {
$pnp.setup({
baseUrl: "/bdm/business-development/Completed%20Submissions/"
});
$pnp.sp.web.getFolderByServerRelativeUrl("/bdm/business-development/Completed%20Submissions/" + folderName).files.orderBy("Name").get().then(function(f) {
var files = '';
$.each(f, function(index, value){
var filesHtml = "<div class='file'>" +
"<a target='_blank' href='" + value.ServerRelativeUrl + "?web=1'><img src='//PublishingImages/wordThumbSmall.png'/></a>" +
"<a target='_blank' href='" + value.ServerRelativeUrl + "?web=1'><p id='fileTitle'>" + value.Title + "</p></a>" +
"</div>";
files = files + filesHtml;
});
$(".Modalbody").append(files);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><div id="x">×</div></button>
<h4 class="modal-title">
</h4>
</div>
<div class="modal-body">
<div class="FT-main-category" style="margin-top:0px;">
<div class="FT-main-header ms-WPBody"><strong><span style="color: white;">Files</span></strong></div>
<div class="Modalbody">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Related

Ajax post request to .NET Core action and getting result not working

I need to implement email sending modal popup and I'm almost done except ajax send request not hit to success or failure
When I click the send button (id:end-email) It successfully hit the .NET Core action and action return status correctly.
But the problem is my ajax call not waiting for the result and automatically closing popup which is not required. I need to show the message instead of closing popup.
<div id="sendemail-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="sendemail-window-title">
<div class="modal-dialog" style="width: 50%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" style="font-weight:600;" id="sendemail-window-title">Shipment Request Email </h4>
</div>
<form id="InStockPendingShipments" name="InStockPendingShipments">
<input type="hidden" id="selectedPOIds" name="selectedPOIds" value="" />
<div class="form-horizontal">
<div class="modal-body">
<div class="form-group">
<div class="col-md-2">
<nop-label asp-for="SendEmail.Subject" />
</div>
<div class="col-md-9">
<nop-editor asp-for="SendEmail.Subject" />
<span asp-validation-for="SendEmail.Subject"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<nop-label asp-for="SendEmail.Message" />
</div>
<div class="col-md-9">
<nop-textarea asp-for="SendEmail.Message" />
<span asp-validation-for="SendEmail.Message"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-1">
</div>
<div class="col-md-10">
<ul id="selected-po-list" class="selected-po-list">
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<div class="input-group input-group-short">
<label id="lblSaveResult" name="lblSaveResult" style="margin-top: 10px;font-weight: 500;"></label>
</div>
<div class="form-group">
<div class="col-md-1">
</div>
<div class="col-md-10">
<button class="btn btn-primary" id="send-email">
Send Email
</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#send-email').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("SendInStockRequestEmail","InStockPendingShipments")',
data: emailData(),
success: function (msg) {
alert("111 success");
},
error: function (req, status, error) {
alert(22225,error);
}
})
.done(function () {
alert("success");
})
.fail(function () {
alert(44444,"error");
});
});
});
function emailData() {
var data = {
SelectedPOIds: $("#selectedPOIds").val(),
Message: $('##Html.IdFor(model => model.SendEmail.Message)').val(),
Subject: $('##Html.IdFor(model => model.SendEmail.Subject)').val()
};
addAntiForgeryToken(data);
return data;
}
$('#sendemail-window').on('show.bs.modal', function () {
$('#SendEmail_Message').val('');
document.getElementById("SendEmail_Message").innerHTML = "";
getInStockProductListByIds($("#selectedPOIds").val());
});
function getInStockProductListByIds(selectedPOsIds) {
var idListData = {
Ids: selectedPOsIds
};
addAntiForgeryToken(idListData);
$.ajax({
cache: false,
type: "POST",
url: "#(Url.Action("getInStockProductListByIds", "InStockPendingShipments"))",
data: idListData,
success: function (result) {
if (result.Data != null || result.Data != '') {
$('#selected-po-list').html('');
$('#selected-po-list').delegate('li');
$('#selected-po-list').append('<li class="list-header"><table><tr>' +
'<td style="width: 10%;font-weight: 600;"> SKU </td>' +
'<td tyle="font-weight: 600;">ProductNane</td>' +
'<td style="font-weight: 600;width: 20%;font-weight:600;text-align: right;position: relative;">Quantity</td>' +
'</tr></table ></li> ');
for (var i = 0; i < result.Data.length; i++) {
console.log('electedPOs', result.Data[i].SKU);
$('#selected-po-list').append('<li><table><tr>' +
'<td style="width: 10%;"> <a target="_blank" href="/admin/Product/Edit/' + result.Data[i].ProductId + '">' + result.Data[i].SKU + '</a></td>' +
'<td>' + result.Data[i].ProductNane + '</td>' +
'<td style="width: 20%;font-weight:600;text-align: right;position: relative;"> <div class="product-count">' + result.Data[i].Quantity + '</div></td>' +
'</tr></table ></li> ');
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to find dispatch information.');
return null;
}
});
}
</script>
<style>
.selected-po-list {
list-style: none;
padding-left: 0;
margin-top: 30px;
max-height: 280px;
overflow-y: auto;
}
.selected-po-list li {
height: 50px;
padding: 10px;
margin-bottom: 5px;
border: 1px solid #00c0ef47;
}
.selected-po-list li table {
width: 100%;
}
.product-count {
position: absolute;
color: white;
height: 25px;
top: 0;
right: 10px;
text-align: center;
padding: 2px 0 0 0;
width: 25px;
border-radius: 50px;
background-color: #3c8dbc;
}
.list-header {
background-color: #7cc3ff30 !important;
height: 25px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
</style>
</div>
</form>
</div>
</div>
</div>
This is my action and it's working fine it returns string message
public virtual IActionResult SendInStockRequestEmail(string SelectedPOIds, string Message, string Subject)
{
var inStockIds = new List<int>(Array.ConvertAll(SelectedPOIds.Split(','), Convert.ToInt32));
string message = _inStockPendingShipmentService.SendInStockShipmentRequestEmail(inStockIds, Message, Subject);
return Json(new DataSourceResult { Data = message });
}
The default type of <button> is submit which submits the form data to the server . You can use input button instead :
<input type="button" class="btn btn-primary" id="send-email" value="Send Email" />

I am retrieving items from a list and want only 4 to show on my page

I am retrieving items from a list, which has 5 items, but I only want 4 to show and every time I add a new item I want the new item to show first and then the other 3 items to follow and the fifth item must not show.
I have tried .last(), hide() but none of them help me accomplish what I want
<div id="phishing" class="row">
<!--Injected content-->
</div>
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 0; i <4; i++) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.prepend(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
I expect to show only 4 items on the page even if there is more than 4 items. I also want the new item to show first.
I actually get the new items first when I changed the loop to items.length but I only want to show 4 items.
enter image description here
The array has the newest item last, but you're skipping that because you only show the first 4 items. Instead of starting from 0, subtract 4 from the length, and make sure it's at least 0.
let start = Math.max(0, items.length-4);
for (let i = start; i < items.length; i++) {
Here I changed prepend() to append()
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 0; i <4; i++) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.append(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
or this, where I changed your for loop to run in reverse order, while retaining prepend().
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 4; i < -1; i--) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.prepend(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
Either one of these should reverse the order of the items in your array as they are printed to the dom. This is assuming that your existing code correctly prints only 4 items, I didn't see where you specified that it was printing more than 4 items except where you set items.length as the conditional in the for loop, which I'm not doing in these examples.
Also, I don't know what the structure of your items array is, but if the objects in that array have a date or timestamp property, then you can sort the array by that property first before running your for loop, that way you can be certain of the order of your items. However this answer is running on the assumption that you only have Title, Description and Image as object properties because thats all I can see in your code.
Let me know how this goes!

How to add panel before and after panel

Report designer layout contains Bootstrap 3 panels.
Detail panel has Add group button which should add new panels before and after it.
This is implemented in onclick event handler using jquery prepend and append:
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"group expression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
If clicked in Add band button html appears instead of panel.
It looks like jquery preoend and append does not add dom objects work for unknown reason.
How to fix this so that new panels appear before and after detail panel ?
$(function() {
var startpos,
selected = $([]),
offset = { top: 0, left: 0 };
$('#designer-detail-addband').on('click', function () {
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"groupexpression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px"></div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
$(".designer-panel-body").droppable({
accept: ".designer-field"
});
$(".designer-field").draggable({
start: function (event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
selected = $(".ui-selected").each(function () {
var el = $(this);
el.data("offset", el.offset());
});
} else {
selected = $([]);
$(".designer-field").removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function (event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function () {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({ top: elOffset.top + dt, left: elOffset.left + dl });
});
}
});
$(".panel-resizable").resizable({
minWidth: "100%",
maxWidth: "100%",
minHeight: 1
});
});
.panel-resizable {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
position: absolute;
}
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
padding: 0;
}
.designer-panel, .panel-body {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-resizable' style='height:2cm'>
<div class='designer-field' style='left:5px;top:6px;width:180px'>field 1 in group 1 header</div>
<div class='designer-field' style='left:54px;top :36px;width:160px'>field 2 in group 1 header</div>
</div>
<div class='panel-footer'>Group 1 Header</div>
</div>
<div class='panel designer-panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:24px;top:2px;width:140px'>field in detail group </div>
</div>
<div class='panel-footer panel-primary'>Detail <a role="button" id="designer-detail-addband"> Add group</a></div>
</div>
<div class='panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:44px;top:2px;width:140px'>field in group 1 footer</div></div>
<div class='panel-footer panel-warning'>Group 1 Footer</div>
</div>
I think your issue is here:
$parentpanel = $this.parent(".designer-panel");
jQuery parent only goes one level up the DOM, and looking at your HTML the first div with .designer-panel is several levels up from your anchor. If you change it to the code below then you should hopefully get the element you want.
$parentpanel = $this.parents(".designer-panel").get(0);

can't get the right index result with an ajax call

I was trying to iterate the 'streamers' array by the variable showindex but failed,it just shows the first element "monstercat" and last element "amazhs" of the array, using debug in chrome and showindex in the displayResult function always is 0 and 9, can't figure out why. Any ideas?
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
streamers.forEach(function(streamer, index) {
showindex = index;
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamer,
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
});
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
}
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
It's because the calls are all happening at the same time so instantly showindex = 9 a way around this would be to do the incrementation in displayResult though it could still go wrong (but it's less likely).
You probably could change your code entirely to make it use promises which would be a lot safer.
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
streamers.forEach(function(streamer, index) {
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamer,
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
});
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
showindex++;
}
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
Here's another way to do it, it doesn't use foreach but iterates through the array another way. This way is a bit slower but means it doesn't get ahead of itself (you can actually see each one pop in)
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
//Work out if there are any streamers left in the array
function calcStreamers() {
if (showindex < (streamers.length - 1)) {
//if there are add 1 and go get it
showindex++;
streamersGet();
} else {
//if not just stop
return false
}
};
//The get function
function streamersGet() {
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamers[showindex],
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
};
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
//Once the data has been added to the page go and check if there are more to add
calcStreamers();
}
//Initally start by getting the first result
streamersGet();
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
You wanted to iterate through the array correct?
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
$(streamers).each(function(index, streamer){
console.log(streamer+" "+index);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to popup a modal on click of each item which are generated dynamically?

I am trying to get some data from the server. I am displaying it in the form of a list. The list is getting displayed nicely. However, when the user clicks a list-item; the user should see the contents related to that particular list item in a modal. How to do I go about it?
Here is my code:
<!DOCTYPE>
<html>
<head>
<title>Pagination tutorial</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://bootswatch.com/yeti/bootstrap.min.css" type="text/css">
<style>
#pagination div { display: inline-block; margin-right: 5px; margin-top: 5px }
#pagination .cell a { border-radius: 3px; font-size: 11px; color: #333; padding: 8px; text-decoration:none; border: 1px solid #d3d3d3; background-color: #f8f8f8; }
#pagination .cell a:hover { border: 1px solid #c6c6c6; background-color: #f0f0f0; }
#pagination .cell_active span { border-radius: 3px; font-size: 11px; color: #333; padding: 8px; border: 1px solid #c6c6c6; background-color: #e9e9e9; }
#pagination .cell_disabled span { border-radius: 3px; font-size: 11px; color: #777777; padding: 8px; border: 1px solid #dddddd; background-color: #ffffff; }
</style>
</head>
<body>
<div id="articleArea"></div> <!-- Where articles appear -->
<!-- Where pagination appears -->
<div id="pagination">
<!-- Just tell the system we start with page 1 (id=1) -->
<!-- See the .js file, we trigger a click when page is loaded -->
<div></div>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="tuto-pagination.js"></script>
</body>
</html>
My javascript code is as follows:
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="loader-small.gif" alt="" />'); // Display a processing icon
var data = {page: page, per_page: 4}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
console.log('Ajax sent');
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'tuto-pagination.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
var displayData='';
for (var i = 0; i < data.articleList.length; i++) {
var gotData = data.articleList[i];
displayData += '<div class="well well-sm">' + gotData.profile_id + '. <b>' + gotData.first_name + '</b><p>' + gotData.surname + '</p></div>';
$('body').on('click','.well well-sm',function(){
var list = gotData;
openModal(list,data);
});
function openModal(list,data){
$('#myModal .modal-title').html(list.html());
$('#myModal .modal-body').html(data);
$('.modalTrigger').trigger('click');
}
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>First</span></div><div class="cell_disabled"><span>Previous</span></div>';
else pagination += '<div class="cell">First</div><div class="cell">Previous</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage) pagination += '<div class="cell_disabled"><span>Next</span></div><div class="cell_disabled"><span>Last</span></div>';
else pagination += '<div class="cell">Next</div><div class="cell">Last</span></div>';
$('#pagination').html(pagination); // We update the pagination DIV
},
error: function() {
}
});
return false;
});
When you are fetching the information from back-end, create the list as shown in the code below, show only first 4 fields, and add a class hidden to the rest of the 26 fields. Construct the list item as you want it to be. Here I have used p tags inside div.well, where first p-tag is shown and rest of the p-tags are hidden.
Now whenever a user clicks on a div-well (that is a list) I am getting the html data from within it and removing the .hidden class from the p-tags. You can also similarly try having your own html structure(have it in a way so that it is easier to manipulate it).
displayData += '<div class="well well-sm"><p>' + gotData.profile_id + '. <b>' + gotData.first_name + '</b>' + gotData.surname + '</p>';
displayData += '<p class="hidden">'+gotData.address+'</p>'+'<p class="hidden">'+gotData.gender+'</p>'+'<p class="hidden">'+gotData.dob+'</p>';
displayData += '</div>';
Then whenever a user clicks on the list item, fetch the data from the list and show it in a modal, this way you don't have to create multiple div's.
$(function(){
$('body').on('click','div.well.well-sm',function(){
var list = $(this);
var data=list.html();
$('#myModal .modal-title').html('User Information');
$('#myModal .modal-body').html(data);
$('#myModal .modal-body p').removeClass('hidden');
$('.modalTrigger').trigger('click');;
});
});
.margin-top-md{
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
<div class="container-fluid">
<div class="well well-sm margin-top-md">
<p>1. John White</p>
<p class="hidden">Country: UK</p>
<p class="hidden">DOB: 29 July</p>
<p class="hidden">Gender:M</p>
</div>
<div class="well well-sm margin-top-md">
<p>4. Ray</p>
<p class="hidden">Country: IN</p>
<p class="hidden">DOB: 29 Aug</p>
<p class="hidden">Gender: M</p>
</div>
<div class="well well-sm margin-top-md">
<p>3. Nick Cole</p>
<p class="hidden">Country: US</p>
<p class="hidden">DOB: 29 Sep</p>
<p class="hidden">Gender:M</p>
</div>
</div>
<button type="button" class="btn btn-primary btn-lg hidden modalTrigger" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
$(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
$('#pagination').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="loader-small.gif" alt="" />'); // Display a processing icon
var data = {page: page, per_page: 4}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
console.log('Ajax sent');
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'tuto-pagination.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
var displayData='';
for (var i = 0; i < data.articleList.length; i++) {
var gotData = data.articleList[i];
displayData += '<div class="well well-sm"><p>' + gotData.profile_id + '. <b>' + gotData.first_name + '</b>' + gotData.surname + '</p>';
displayData += '<p class="hidden">'+gotData.address+'</p>'+'<p class="hidden">'+gotData.gender+'</p>'+'<p class="hidden">'+gotData.dob+'</p>';
displayData += '</div>';
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>First</span></div><div class="cell_disabled"><span>Previous</span></div>';
else pagination += '<div class="cell">First</div><div class="cell">Previous</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage){
pagination += '<div class="cell_disabled"><span>Next</span></div><div class="cell_disabled"><span>Last</span></div>';
}
else {
pagination += '<div class="cell">Next</div><div class="cell">Last</span></div>';
}
$('#articleArea').html(displayData);//replacing img with data
$('#pagination').html(pagination); // We update the pagination DIV
}
},
error: function() {
//your code
}
});
return false;
});
$('body').on('click','div.well well-sm',function(){
var list = $(this);
$('#myModal .modal-title').html('User Information');
$('#myModal .modal-body').html(list.html());
$('#myModal .modal-body p').removeClass('hidden');
$('.modalTrigger').trigger('click');
});
});

Categories