Datatables updating only rows without reloading table - javascript

BACKGROUND:
I have a small jquery app that contains widgets. There are 2 types of widgets in this app and they are counter widgets and grid widgets. For grid widgets i am utilizing dataTables.
My app basically connects to a server and recieves various information such as widget names etc. So based on the information received i dynamically create pages for each widget. Things are working fine at the moment but i am facing a little problem.
Problem
The issue i have right now is to do with my grid widgets which utilize dataTables api.From my server I receive the grid information in this format.
//EXAMPLE INPUT
/*
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<head>
<column width="55" type="ro" align="left" sort="str">Player</column>
<column width="55" type="ro" align="left" sort="str">State</column>
<column width="55" type="ro" align="left" sort="str">Points</column>
</head>
<row id="1">
<cell>Lebron King James</cell>
<cell>Best Mode</cell>
<cell>45</cell>
</row>
</rows>
*/
Then i parse it to the appropriate table format (function createTableStringFromXML) so it works with the datatables.
My table is reloading every 3 seconds. So this is the problem.
Eventhough i want my table to update i think reloading the entire table is bad because not only does it look weird but i think it is not necessary. I was wondering is there way i can write some function that compares the old table with the new updated table and only updates rows that need update? So this way the entire table it self is not loaded?
MY HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>NBA Fanatico</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="themes/tdMobile.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
<link rel="stylesheet" type="text/css" href="cssfinal/style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="dhtmxSuite/dhtmlxWindows/codebase/dhtmlxcommon.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="jquery.ui.touch-punch.min.js"></script>
<!-- MAIN JS SCRIPT CONTANS CODE FOR COUTNER WIDGETS, TABLES , AJAX REQUEST FOR GETTING DATA-->
<script src="dynamic.js"></script>
<!-- SCRIPTS FOR DATA TABLES -->
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
</head>
<body>
<!-- PAGE 1 -->
<div data-role="page" data-theme="a" id="page1">
<!-- <div data-role="header" data-position="fixed">
<h1></h1>
</div> -->
<div data-role="content" data-theme="a">
<div class="login-box" id="login">
<div id="loginprompt">
<div id="header">
<h3>Basketball Fanatico</h3>
</div>
</div>
<form method="GET">
<div id="username" data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" />
</div>
<div id="password" data-role="fieldcontain">
<input type="password" name="password" id="txtId" placeholder="Password"/>
</div>
<div id ="loginbtn">
<a data-role="button" id="log" data-theme="a" href="#page2" data-transition="slide">LOGIN</a>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<!-- PAGE 2 -->
<div data-role="page" id="page2">
<div data-role ="header" data-position="fixed" data-theme="a">
<a data-iconpos="notext" href="#panel" data-role="button" data-icon="bars"></a>
<h1 class="ui-title" role="heading">Basketball Fanatico</h1>
<div class="ui-btn-right" data-type="horizontal">
<a data-iconpos="notext" href="#page2" data-role="button" data-icon="home" ></a>
<a data-iconpos="notext" href="#page1" data-role="button" data-icon="delete" ></a>
</div>
</div>
<div data-role="content" id="page2content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider" data-theme="a">WELCOME!</li>
<li>Use the menu on the left to navigate <br />and configure the various options.</li>
</ul>
</div>
</div>
<div data-role="panel" id="panel" data-position="left" data-theme="a" data-display="push">
<!-- <div> -->
<div id="nav"><h3>Navigation</h3>
<hr>
<label>
<input id="chkSort" type="checkbox" checked="true" />Allow sorting</input>
</label>
<hr>
</div>
<div id="items" data-role="button">
<!-- Insert Parsed Widget Names Here -->
LOG OUT
</div>
<!-- </div> -->
</div>
</body>
</html>
MY JS
var widgetNames = new Array();
var widgetId = new Array();
var pageId = ''
$( document ).on( "pagecreate", function() {
$( "body > [data-role='panel']" ).panel().enhanceWithin();
//Format the grid as required
$('#example2').dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
});
$(document).on('pagecreate', '#page1', function() {
// $( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
// pageId = $('body').pagecontainer('getActivePage').prop("id");
// alert( "The page id of this page is: " + pageId );
// });
$("#log").on('click', function(){
$.ajax({
url: "script.login",
type: "GET",
data: { 'page':'create_user', 'access':'user','username':$("input[name='username']").val(), 'password':$("input[name='password']").val()},
dataType: "text",
success: function (html) {
//console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
//Get each widget name and ID and assign to values in an array
for(var i =0;i<res.length;i++){
//alert(res[i]);
var temp = res[i].split(',');
if(temp.length >= 3){
widgetNames[i] = (temp[2].replace('");','')).replace('"','');
widgetId[i] = temp[1].replace("'","").replace("'","").replace(/ /g,'');
}
}
var AllWidgets = ''
var testwidget = new Array();
//Loop through the html returned and get the data relevant to each widget... save in temp array
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for(var i =0;i<tempWidgetContent.length;i++){
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{')+1);
//alert(widgetContent);
//This alone handles coutners...
testwidget[i] = widgetContent.replace("site +","");
//replace the code for a grids...
if(testwidget[i].indexOf('grid') > 0){
testwidget[i] = CreateGridUpdateFunction(testwidget[i],i);
}
}
var widgetPart = new Array();
//Assume we have widget names, ids, and loading data in 3 arrays
//Loop through and create the necessary page.
for(var i = 0; i<widgetNames.length; i++){
if(testwidget[i].indexOf('hi') > -1){
// alert('WORKING');
var pageHeaderPart = "<div data-role= 'page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header' id='header1' data-position='fixed' data-theme='a'><a href='#panel' data-icon='bars' data-iconpos='notext' class='ui-btn-left'></a><a href='#' data-icon='search' id='search' data-iconpos='notext' class='ui-btn-left' style='margin-left: 35px'></a><h1>BASKETBALL FANATICO</h1><a href='#page1' data-icon='delete' data-iconpos='notext' class='ui-btn-right'></a><a href='#page2' data-icon='home' data-iconpos='notext' class='ui-btn-right' style='margin-right: 35px;'></a></div><div data-role='content'>";
}
else{
var pageHeaderPart = "<div data-role='page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header'data-position='fixed' data-theme='a'><a data-iconpos='notext' href='#panel' data-role='button'data-icon='bars'></a><h1 class='ui-title'role='heading'>BASKETBALL FANATICO</h1><div class='ui-btn-right' data-type='horizontal'><a data-iconpos='notext' href='#page2' data-role='button'data-icon='home'style=\" margin-right:5px; \"></a><a data-iconpos='notext' href='#page1' data-role='button'data-icon='delete'></a></div></div><div data-role='content'>";
}
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
var check = "<div data-role='tbcontent'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"";
}
var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"</div>";
if(testwidget[i].indexOf('counterValue') > 0){
// alert('i am a counter');
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '$(\"#widgetContainer_'+widgetId[i]+'").html(counterValue);' + '}' + '</SCRIPT>';
}
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
widgetPart[i] = '<DIV id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '}' + '</SCRIPT>';
}
else {
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'>I dont know what I am</DIV>';
}
AllWidgets +='<a href="#'+widgetId[i]+'" class="widgetLink" data-theme="b" data-role="button" >'+widgetNames[i]+'</a>';
var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
//Widget Update Function
function UpdateActivePage(){
//get active page
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
//figure out index
var idx;
for (var i=0; i<widgetId.length; i++){
if (widgetId[i] == pageId){
idx = i;
break;
}
}
//alert(pageId);
//run your update
//alert("RUNNING:");
eval(testwidget[idx]);
//alert('Updateing active page');
$("#widgetContainer_" + pageId).html(counterValue);
$('#grid_'+idx).dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
}
function CreateGridUpdateFunction(oldUpdatefunction,thisWidgetID)
{
var updateLines = oldUpdatefunction.split("\n");
var updateFunctionCode = "";
for (var i=0; i<updateLines.length;i++)
{
if(updateLines[i].indexOf(" var url = ") > 0)
{
var updateURL = updateLines[i];
if(updateURL.indexOf("&windowWidth=") > 0){
updateURL = updateURL.substr(0,updateURL.lastIndexOf("&windowWidth=")) + "';";
}
updateFunctionCode += updateURL;
updateFunctionCode += " var loader = dhtmlxAjax.getSync(url);";
updateFunctionCode += " if(loader.xmlDoc.responseText.length > 0){";
updateFunctionCode += " counterValue = createTableStringFromXML(loader.xmlDoc.responseText,"+thisWidgetID+");";
updateFunctionCode += " } ";
}
}
return "var counterValue = \"hi\"; "+updateFunctionCode ;
}
$(":mobile-pagecontainer" ).on( "pagechange", function() { UpdateActivePage(); } )
setInterval(UpdateActivePage, 3000);
}
});
});
});
//Returns a bool indicated if the (space trimmed) string starts with needle.
function startsWith(searchString,searchVal){
var search = searchString.trim();
return search.indexOf(searchVal) >= 0;
}
function createTableStringFromXML(serverXML,thisWidgetID){
console.log(serverXML);
var xmlLines = serverXML.split("\n");
var returnTable = "";
for (var i=0; i<xmlLines.length;i++)
{
if(startsWith(xmlLines[i],"<rows"))
{
returnTable += "<table cellpadding=\"2\" cellspacing=\"2\" border=\"0\" class=\"display\" id=\"grid_"+thisWidgetID+"\" width=\"100%\">";
}
else if(startsWith(xmlLines[i],"</rows>"))
{
returnTable += "</tbody></table>";
}
else if(startsWith(xmlLines[i],"<head>"))
{
returnTable += "<thead><tr>";
}
else if(startsWith(xmlLines[i],"</head>"))
{
returnTable += "</tr></thead><tbody>";
}
else if(startsWith(xmlLines[i],"<column"))
{
returnTable += "<th>"+xmlLines[i].match(/>(.*?)</i)[1]+"</th>";
}
else if(startsWith(xmlLines[i],"<row"))
{
returnTable += "<tr>";
}
else if(startsWith(xmlLines[i],"</row"))
{
returnTable += "</tr>";
}
else if(startsWith(xmlLines[i],"<cell"))
{
returnTable += "<td>"+xmlLines[i].match(/>(.*?)</i)[1]+"</td>";
}
console.log(returnTable);
}
return returnTable ;
}
Please advice on how to achieve this. I am sorry if you have not understood my question so please ask me again. I am only using HTML and JS for couple of months so i am band new to this and that also might be the reason why my question might sound silly to some of you so sorry in advance. I apologize for my poor english please let me know if you dont understand. Thanks.

Updating the table every 3 seconds could cause performance issues, especially if you have lots of rows!
If you want to do it, you can iterate through the rows in the update XML and then write the values to the individual cells in the table.
DEMO
In my example, the table is already there with row ids as data attributes on the row element. I am updating once on a button click instead of every 3 seconds on a timer, but the parsing would be the same.
$("#update").on("click", function(){
var $trows= $('#example tbody tr');
var xmlDoc = $.parseXML( xmlstring );
var $xml = $( xmlDoc );
$xml.find("row").each(function(index){
var id = $(this).prop("id");
var $cells = $(this).find("cell");
var c1 = $cells.eq(0).text();
var c2 = $cells.eq(1).text();
var c3 = $cells.eq(2).text();
//get row in table with this id
var $rowtd = $('#example tbody [data-id=' + id + '] td');
$rowtd.eq(0).text(c1);
$rowtd.eq(1).text(c2);
$rowtd.eq(2).text(c3);
});
});
The code loads the XML string into an XmlDocument and then creates a jQuery object from the document. Next I iterate through all the Xml Nodes called "row" getting the id and the 3 cell texts. Then I find the row in the existing table with the same Id and write the texts into the existind TDs in the row.
You will need to test the performance of this given the normal number of rows you have and the types of devices you plan to support.

Related

How can i show flipbook when user clicks on flipbook's icons in jquery

Hope you all are fine. I Stuck in one problem from last three days and can't understand what should i do. If you can kindly help me. This is my code when user click on publication button a carousel of images become shown in the screen and when user click on these images it becomes filpbook of that images. The Problem in that is it works fine in first time and when user close that open flipbook and want to open new flipbook that old one still there and new clickable flipbook's icon didn't open in form of flipbook. I hope you people understand my question what i want to ask ? I also attached some images of results and also paste code so that you could relate to it.
Image Carousel (flipbook's icon)
flipbook open as expected when user click on it first time
Image Carousel (flipbook's icon) User want to open new flipbook from carousel
New flipbook open but old flipbook didn't disappear it still open. New Flipbook should open instead of old one and hide old one
$(document).ready(function() {
getPdfsIcons()
$("#back").hide();
// Load the HTML4 version if there's not CSS transform
// $("#flipview").hide();
// var carousel = $("#carousel").slidingCarousel({
// squeeze: 100
// });
$("#back").click(function() {
$("#flipview").hide();
$("#carousel").hide();
$("#pub").hide();
$("#switch-field").hide();
$("#close-btn").hide();
loadMain();
});
$("#close-btn").hide();
});
function getPdfsIcons() {
var dir;
var choosenlanguage = $("input[type='radio']:checked").val();
if (choosenlanguage == "e")
dir = "assets/Publications/English/";
else if (choosenlanguage == "a")
dir = "assets/Publications/Arabic/";
else if (choosenlanguage == "f")
dir = "assets/Publications/French/";
var fileextension = ".jpg";
var inc = 0;
$.ajax({
url: dir,
success: function(data) {
$(data)
.find("a:contains(" + fileextension + ")")
.each(function(i) {
var filename = this.href
.replace(window.location.host, "")
.replace("http://", "");
var folder = filename;
$(".carousel").append(
"<div id='slide" + i + "' class='slide' onClick=getAllrecords(document.getElementById('slide" + i + "').style.opacity,'" + folder.replace("assets/Publications/English/", "").replace(".jpg", "").replace("/", "") + "','" + i + "');><p> <span> " + filename + " </span> </p></div>" + "</div>"
);
});
},
});
}
function getAllrecords(opacity, foldername, x) {
if (opacity == 1) {
var choosenlanguage = $("input[type='radio']:checked").val();
if (choosenlanguage == "e")
dir = "assets/Publications/English/" + foldername + "/";
else if (choosenlanguage == "a")
dir = "assets/Publications/Arabic/" + foldername + "/";
else if (choosenlanguage == "f")
dir = "assets/Publications/French/" + foldername + "/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function(data) {
$(data)
.find("a:contains(" + fileextension + ")")
.each(function(i) {
var filename = this.href
.replace(window.location.host, "")
.replace("http://", "");
$(".flipbook-pages").append("<div class='flipImgs" + x + "'><img src='" + filename + "' width='600' height='600' /></div>");
$(".flipbook-thumbnail").append(
"<li>" +
"<img class='page-" +
++i +
"' src='" +
filename +
"' width='200' height='200' ' />" +
"</li>"
);
});
},
});
$("#flipview").show();
$("#carousel").hide();
$("#pub").hide();
$("#switch-field").hide();
$("#close-btn").show();
$("#close-btn")
.click(function() {
//window.location.href = "home.html"
$("#flipview").hide();
//$(".mainmenu_row1").hide()
//$(".mainmenu_row2").hide()
$("#pub").show();
$("#carousel").show();
//$(".flipbook-pages").empty();
//$(".flipbook-thumbnail").empty();
// var rangeObj = new Range();
// // Select all of theParent 's children
// rangeObj.selectNodeContents(document.getElementById('flipbook-pages'));
// // Delete everything that is selected
// rangeObj.deleteContents();
});
yepnope({
test: Modernizr.csstransforms,
yep: ["assets/js/turn.min.js"],
nope: ["assets/js/turn.html4.min.js"],
both: [
"assets/css/basic.css",
"assets/css/magazine.css",
"assets/js/magazine.js",
],
complete: loadApp,
});
}
}
function loadApp() {
// Create the flipbook
$(".flipbook-pages").turn({
// Width
width: 922,
// Height
height: 600,
// Elevation
elevation: 50,
// Enable gradients
gradients: true,
// Auto center this flipbook
autoCenter: true,
});
$(".thumbnails").click(function(event) {
var page;
if (
event.target &&
(page = /page-([0-90]+)/.exec($(event.target).attr("class")))
) {
$(".flipbook-pages").turn("page", page[1]);
}
});
$(".next-button")
.bind("mouseover", function() {
$(this).addClass("next-button-hover");
})
.click(function() {
$(".flipbook-pages").turn("next");
});
$(".previous-button")
.bind("mouseover", function() {
$(this).addClass("previous-button-hover");
})
.click(function() {
$(".flipbook-pages").turn("previous");
});
}
function loadMain() {
window.location.href = "home.html";
// $("icon_1").removeClass("animate__fadeOut");
// // $("icon_2").removeClass("animate__fadeOut");
// // $("icon_3").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_4").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_5").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_6").removeClass("animate__animated animate__swing animate__fadeOut");
// document.getElementById("icon_1").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_3").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_4").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_5").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_6").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_2").classList.add("animate__animated animate__swing animate__fadeIn");
}
function onBounce(id) {
document.getElementById(id).classList.add("animate__bounceOut");
if (id = "icon_2") {
getPdfsIcons();
document.getElementById("icon_1").classList.add("animate__fadeOut");
document.getElementById("icon_3").classList.add("animate__fadeOut");
document.getElementById("icon_4").classList.add("animate__fadeOut");
document.getElementById("icon_5").classList.add("animate__fadeOut");
document.getElementById("icon_6").classList.add("animate__fadeOut");
document.getElementById(id).addEventListener('animationend', () => {
// document.getElementById("mainmenu").style.setProperty('--animate-duration', '0.1s');
// document.getElementById("mainmenu").classList.add("animate__fadeOut");
document.getElementById("pub").style.setProperty('display', 'block');
document.getElementById("pub").classList.add("animate__zoomInRight");
$("#back").show();
var carousel = $("#carousel").slidingCarousel({
squeeze: 100
});
// do something animate__zoomInRight
});
$(".carousel").append(
"<div class='navigate-left'><img src='assets/images/backward.png' /></div>" +
"<div class='navigate-right'><img src='assets/images/forward.png' /></div>"
);
}
}
function language(lang) {
if (lang == 0) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/ebv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/ebv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/ebv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/ebv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/ebv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/ebv7.png')";
} else if (lang == 1) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/abv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/abv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/abv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/abv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/abv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/abv7.png')";
} else if (lang == 2) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/fbv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/fbv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/fbv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/fbv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/fbv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/fbv7.png')";
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="assets/css/main.css" />
<link rel="stylesheet" href="assets/css/animate.min.css" />
<link rel="stylesheet" href="assets/css/experiment.css" />
<link type="text/css" rel="stylesheet" href="assets/css/jquery.ui.css">
</link>
<link type="text/css" rel="stylesheet" href="assets/css/default.css">
</link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/modernizr.2.5.3.min.js"></script>
<script type="text/javascript" src="assets/js/hash.js"></script>
<script type="text/javascript" src="assets/js/turn.html4.js"></script>
<script type="text/javascript" src="assets/js/zoom.js"></script>
<script type="text/javascript" src="assets/js/scissor.min.js"></script>
<script src="assets/js/jquery-slidingCarousel.js" type="text/javascript"></script>
<link rel="stylesheet" href="assets/css/sliding-carousel.css" />
<!-- <link rel="manifest" href="/manifest.json" /> -->
<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png" />
<meta name="theme-color" content="#ffffff" />
<!-- <script src="assets/js/app.js"></script> -->
<title>Interactive Apps</title>
<style>
.scrollmenu {
background-color: white;
overflow: auto;
white-space: nowrap;
}
.scrollmenu li {
display: inline-block;
color: white;
padding: 14px;
text-decoration: none;
}
</style>
</head>
<body>
<div class="fullscreen">
<div class="row">
<div class="logo">
<img src="assets/images/logo.png" alt="logo image" />
</div>
<div id="switch-field" class="switch-field">
<input type="radio" id="radio-three" onclick="language(0);" name="langchoice" value="e" checked />
<label for="radio-three">English</label>
<input type="radio" id="radio-four" name="langchoice" onclick="language(1);" value="a" />
<label for="radio-four">عربى</label>
<input type="radio" id="radio-five" name="langchoice" onclick="language(2);" value="f" />
<label for="radio-five">Français</label>
</div>
<div class="pole-clock">
<div id="clock">
<div id="hour"><img src="assets/images/small_hand.png" /></div>
<div id="minute"><img src="assets/images/long_hand.png" /></div>
<div id="second"><img src="assets/images/sec_hand.png" /></div>
</div>
</div>
</div>
<div class="footer">
<img src="assets/images/Path 60.png" alt="footer image" />
</div>
<div id="mainmenu" class="animate__animated">
<div class='mainmenu_row1'>
<div id="icon_1" class='menu1 animate__animated animate__swing' onclick="onBounce('icon_1');">
</div>
<div id="icon_2" class='menu2 animate__animated animate__swing' onclick="onBounce('icon_2');">
</div>
<div id="icon_3" class='menu3 animate__animated animate__swing' onclick="onBounce('icon_3');"> </div>
</div>
<div class='mainmenu_row2'>
<div id="icon_4" class='menu4 animate__animated animate__swing' onclick="onBounce('icon_4');"> </div>
<div id="icon_5" class='menu5 animate__animated animate__swing' onclick="onBounce('icon_5');"> </div>
<div id="icon_6" class='menu6 animate__animated animate__swing' onclick="onBounce('icon_6');"> </div>
</div>
</div>
<!-- publications -->
<div id="pub" style="display: none;" class="pub animate__animated">
<div id="carousel" class="carousel">
</div>
</div>
<div id="flipview" class="flipview">
<div class="flipbook-viewport">
<div class="container">
<div class="flipbook">
<div id="flipbook-pages" class="flipbook-pages" style="margin-top: -8rem">
<div ignore="1" class="next-button"></div>
<!-- Previous button -->
<div ignore="1" class="previous-button"></div>
</div>
<button type="button" class="btn close" id="close-btn" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true" style="font-size: -webkit-xxx-large">×</span>
</button>
</div>
</div>
</div>
<div class="thumbnails" style="padding-top: 44rem">
<div>
<ul class="flipbook-thumbnail scrollmenu"></ul>
</div>
</div>
</div>
<div id="back" class="back"></div>
</div>
</body>
</html>

Pass only selected checkboxes and attributed input textboxes via jQuery?

I have a table that shows items and the current inventory. Next to each row of inventory, I have a checkbox and a textbox.
The webpage shows the current inventory and gives options for removing selected stock from inventory. So basically checking out items from stock.
I'd like to be able to pass both the selected item and the inputted amounts to be removed from stock via jQuery but I am having trouble finding the best way to 'serialize' both the checkbox and the text input.
I've tried a number of strategies based off other SO questions, but I only seem to be able to grab either the checked box value or all of the text input values but not the checked box value and only the input value of the checked box.
What I am trying to get:
Checked Apple & entered 5: box=Apple&amt=5
What I've tried (seen in on('submit') function):
What I am getting when using var details = $('input[name="box"]:checked').serialize();:
Checked Apple & entered 5: box=Apple
What I am getting when using var details = $('#checkout_form').serialize();
or
var details = $('input[id="amt"]').serialize();
:
Checked Apple & entered 5: Apple=5&Banana=&Corn=&Deli%20Sandwich=&....
Here is the jQuery code for displaying the table from JSON data and for passing the data to PHP:
var url = 'get_students.php';
var $list = $('#inventory');
$(document).ready(function() {
$.ajax({
type: 'POST',
url: url,
data: {
command: 'get_inventory',
},
beforeSend: function() {
$list.html('<div id="load" class="spinner-border text-muted"></div>');
},
success: function(data) {
console.log(data);
DISPLAY_INVENTORY(data);
$('#load').remove();
},
fail: function() {
$list.html('Could not get data ...');
},
});
});
function DISPLAY_INVENTORY(JSON_DATA) {
var COL_NAMES = ['Select', 'Item', 'Inventory', 'Amount'];
var data = jQuery.parseJSON(JSON_DATA);
var $TABLE_OBJ = $('<table class="table table-striped" >');
$TABLE_OBJ.attr('id', 'student_table');
$list.append($TABLE_OBJ);
// $(output).append($TABLE_OBJ);
//Print a table header
var $ROW_OBJ = $('<tr>');
var $THEAD = $('<thead class="thead-light">');
$THEAD.append($ROW_OBJ);
$TABLE_OBJ.append($THEAD);
for (var j = 0; j < COL_NAMES.length; j++) {
var $TB_HEADER = $('<th>');
$TB_HEADER.html(COL_NAMES[j]);
$ROW_OBJ.append($TB_HEADER);
}
$TBODY = $('<tbody>');
//Print rows
for (var i = 0; i < data.length; i++) {
if (i == data.length - 1) {
$TABLE_OBJ.append($TBODY);
}
$ROW_OBJ = $('<tr>');
$TBODY.append($ROW_OBJ);
$BOX_OBJ = $('<input name="box" class="form-control ml-4" type="checkbox">');
$ROW_OBJ.append($BOX_OBJ);
//Print columns
$.each(data[i], function(key, value) {
// if (i % 2 == 0) {
// var ITEM_NAME = value;
// }
if (key === 'item') {
rowItemName = value;
}
$COL_OBJ = $('<td>');
$INP_OBJ = $('<input id="amt" class="text-center form-control" type="text" size="3">');
if (!$INP_OBJ.attr('name') || !($BOX_OBJ.attr('value'))) {
$INP_OBJ.attr('name', rowItemName);
$BOX_OBJ.attr('value', rowItemName);
// $INP_OBJ.attr('id', ITEM_NAME);
}
// $INP_OBJ.attr('name', ITEM_NAME);
// $INP_OBJ.attr('id', ITEM_NAME);
$COL_OBJ.html(value);
$ROW_OBJ.append($COL_OBJ);
});
$ROW_OBJ.append($INP_OBJ);
}
}
// add form to checkout
$('#checkout_form').on('submit', function(e) {
e.preventDefault();
// var details = $('#checkout_form').serialize();
// var details = $('input[name="box"]:checked', 'input[id="amt"]').serialize();
// var details = $('input[name="box"]:checked').serialize();
var details = $('input[id="amt"]').serialize();
console.log(details);
//Update the info into database table
$.post(url, {
command: 'update_inventory',
log_data: details,
},
function(data, status) {
console.log('Data: ' + data + '\nStatus: ' + status);
//$status.html(status + ": " + data);
});
});
Here is the JSON data if needed:
[{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- ------------------------------------- -->
<!-- LOAD EXTERNAL STYLES -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Fonts and Icons -->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/octicons/8.5.0/build.css">
<link rel="icon" href="https://txwes.edu/media/twu/style-assets/images/favicon.ico" type="image/x-icon">
<!-- ------------------------------------- -->
<style>
html,
body {
height: 100%
}
body {
background: url('img/bg.jpg');
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.fas {
color: black !important
}
</style>
<title>Checkout</title>
</head>
<body>
<!-- Header -->
<div class="jumbotron text-center h-auto " style="background: rgba(244, 226, 66,0.5); border-bottom: 5px outset rgb(244, 226, 66);">
<img src="img/ramlogo3.png" alt="ramlogo">
</div>
<div class="container">
<div class="jumbotron text-center">
<h1>Checkout</h1>
<form id="checkout_form" method="post">
<div id="inventory" class="text-center border border-primary rounded p-3" style="overflow-y:scroll; overflow-x:hidden; height:400px;"></div><br>
<button class="btn btn-primary" type="submit" name="button">Checkout</button>
</form>
</div>
</div>
</body>
<script type="text/javascript">
...see above...
</script>
</html>
Please let me know if any more explanation is needed, thank you for the help!
To serialize your data in a single row you can try this code:
var details = $('input[name="box"]:checked').closest("tr").find("input").serialize();

Working with multiple arrays after splitting (jQuery)

I am trying to create a web page that takes data from a CVS file and creates a custom for each row of content in the CSV file. I used jQuery to import CSV file and split the data it into an array:
promise = $.ajax({
type:"GET",
dataType:"text",
url:"data.csv",
cache:false
});
promise.done(function(data){
//Parse CSV File
//split on new line
var dataArr = data.split("\n");
console.log(dataArr);
Then I am using $.each to split each line into an array.
//for each line in array
$.each(dataArr,function(){
var valArr = this.split(",");
screenshot of arrays
After that, I would like to take each created array and use it for creating my custom element. However, I can't figure out how to access each created array individually. If I access first item in the array by using valArr[0], I get results for the entire column A (instead of row 1, column A) in my CSV file. I'm new to Javascript, so I'm completely stuck here. Please point me in the right direction.
Thank you!
Update: added the HTML code I am using to insert the data from each row into.
<!doctype html>
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<!--Content start -->
<div class="container-fluid">
<div class="row">
<!--Catalog content start -->
<div class="col">
<div class="row allMyContent">
<!-- Card start -->
<div class='card mb-4 box-shadow col-5 ml-4'>
<div class="card-header" style="background-color: #fff;">
<!-- Link 1, 2, 3 etc go here (id #contentLink) -->
Link 1
<!-- Course 1, 2, 3 etc go here (id #contentTitle) -->
<h5 class="my-0 font-weight-normal mr-5" id="contentTitle">Course 1</h5>
</div>
<div class="card-body">
<div>
<!-- Time and type go here (id #contentLength and #contentType) -->
<p><span class="mr-2" id='contentType'>Type 1</span> | <span class="ml-2"><span id='contentLength'></span> 20 min</span>
</p>
</div>
<div>
<!-- Description goes here (id #contentDescription) -->
<p id='contentDescription'>Description 1</p>
</div>
</div>
<div class="card-footer row" style="font-size: 0.85em;">
<!-- Audience, dates goe here (id #contentAudience #date1 #date2) -->
<small class="col" id='contentAudience'>Audience: HR</small>
<small class="col" id='date1'>Created: Jul-17</small>
<small class="col" id='date2'>Updated: Dec-17</small>
</div>
</div>
<!-- Card end -->
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
Seems you got the .split() done right. To recap:
.split("\n") will get you CSV lines Array (your dataArr)
for looping dataArr you have access to each individual line (I'll use JS's .map())
splitting each line using .split(",") will give you an array of cells
for looping your cells will give you access to each individual cell (let's use .map() again)
// I'll hardcode this CSV data; you, use AJAX as you do already...
const data = `Course A,Link 1,Type1,20,Description 1,HR,Jul-17,Dec-17
Course B,Link 2,Type1,30,Description 2,HR,Oct-17,Dec-18
Course C,Link 3,Type2,60,Description 3,HR,Nov-17,Dec-19`;
const dataArr = data.split("\n");
// let's create rows and cells
document.getElementById("courses").innerHTML = dataArr.map( row =>
// row is still a comma concatenated string.
// Let's split by comma to get cells
`<tr>
${ row.split(",").map( cell => `<td>${cell}</td>`).join("") }
</tr>`
).join(""); // join rows Array into String;
table{
border-collapse: collapse;
width: 100%;
}
th, td{
padding: 5px 10px;
border: 1px solid #eee;
}
<table>
<thead>
<tr>
<th>Course</th>
<th>Link</th>
<th>Type</th>
<th>Duration</th>
<th>Description</th>
<th>CC</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody id="courses"></tbody>
</table>
If the above seems a bit cryptic here's an example with Array.prototype.forEach()
// I'll hardcode this CSV data; you, use AJAX as you do already...
const data = `Course A,Link 1,Type1,20,Description 1,HR,Jul-17,Dec-17
Course B,Link 2,Type1,30,Description 2,HR,Oct-17,Dec-18
Course C,Link 3,Type2,60,Description 3,HR,Nov-17,Dec-19`;
const lines = data.split("\n");
let HTML = ""; // We'll concatenate HTML string along the way
// let's create rows and cells
lines.forEach(function(line, i) { // Concatenate rows
const items = line.split(","); // (our Array of cells)
HTML += "<tr>"; // open row
HTML += "<td>"+ (i+1) +"</td>" // Insert a hardcoded TD with index
items.forEach(function(item, j) { // than concatenate our remaining cells
HTML += "<td>"+ item +"</td>";
});
HTML += "</tr>"; // Close row
});
document.getElementById("courses").innerHTML = HTML; // Finally, append our HTML string
table{
border-collapse: collapse;
width: 100%;
}
th, td{
padding: 5px 10px;
border: 1px solid #eee;
}
<table>
<thead>
<tr>
<th>#</th>
<th>Course</th>
<th>Link</th>
<th>Type</th>
<th>Duration</th>
<th>Description</th>
<th>CC</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody id="courses"></tbody>
</table>
if valArr[0] contains whole A column why not iterate over it like this:
for(var column = 0; column < valArr.length; column++){
var currentColumn = valArr[column];
for(var item = 0; item < currentColumn.length; item++){
console.log(currentColumn[item]);
}
}
code above will iterate every column and over every item in every column, if you want to save whole row in variable you can do it like this:
function getRow(varArr, id){
var retval = [];
for(var column = 0; column < valArr.length; column++){
var currentColumn = valArr[column];
retval.push(currentColumn[id]); //add some checking if id is really present in this array
}
return retval;
}
code above will return something like this:
[column_A_item_with_id, column_B_item_with_id, column_C_item_with_id, ...]
After modifying the code suggested by Roko and spending a bunch of time trying to figure out why it's not working, I realized I wasn't building the HTMl correctly. Here is the final result.
const data = `Course A,Link 1,Type1,20,Description 1,HR,Jul-17,Dec-17
Course B,Link 2,Type1,30,Description 2,HR,Oct-17,Dec-18
Course C,Link 3,Type2,60,Description 3,HR,Nov-17,Dec-19`;
const dataArr = data.split("\n");
//Parse CSV File
//split on new line
const lines = data.split("\n");
let HTML = '';
//for each line in array
lines.forEach(function(line, i) {
var contentCards = line.split(",");
HTML += '<div class="card mb-4 box-shadow col-5 ml-4">';
HTML += '<div class="card-header">'
HTML += '<h5 class="my-0 font-weight-normal mr-5" style="color: #ff8f00;">'
HTML += '<a href="'
HTML += contentCards[1];
HTML += '" class="float-right ml-3" id="copyLink" style="color: #00a4b4; font-size: 1.2rem;"><i class="fas fa-external-link-square-alt"></i></a>'
HTML += '<a href="'
HTML += contentCards[1];
HTML += '"class="float-right" style="color: #00a4b4; font-size: 1.2rem;"><i class="fas fa-link"></i></a>'
HTML += contentCards[0];
HTML += '</h5>'
HTML += '</div>'
HTML += '<div class="card-body">'
HTML += '<div>'
HTML += '<div class="card-body">'
HTML += '<p><span class="mr-2">'
HTML += ' <p><span class="mr-2 contentType">'
HTML += contentCards[2];
HTML += '</span>|<span class="ml-2"><i class="far fa-clock"></i ><span>'
HTML += contentCards[3];
HTML += ' min</span >'
HTML += '</p>'
HTML += '</div>'
HTML += '<p>'
HTML += contentCards[4];
HTML += '</p>'
HTML += '</div>'
HTML += '<div class = "card-footer row" style = "font-size: 0.85em;" >'
HTML += '</div>'
HTML += '</p>'
HTML += '</div>'
HTML += '</div>'
document.getElementById("courses").innerHTML = HTML;
});
console.log(HTML);
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<div id="courses">
</div>

how to add fade in and fade out

I am stuck with my project.
I need to add to the code below fade-in and fade-out effect by using javascript and css only. please help me.
I created this function to store all the data in the local storage and when I am clicking on the save button I want the note to be added with fade in effect. when I am deleting the note I want it to be deleted in fade out. only the note I am adding or deleting will be added or removed with the effect
this is the function to add the note:
function saveIt() {
var content = document.getElementById("content").value;
var date = document.getElementById("date").value;
var time = document.getElementById("time").value;
var id = Math.floor(Math.random() * 100000); //creating random id number.
var note = { id: id, content: content, date: date, time: time };
notesArray.push(note);
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
for (var i = 0; i < notesNewArray.length; i++) {
theId = notesArray[i].id;
var output = "<div id='justFade'>" + "<div class='main col-xm-12 col-sm-6 col-md-4 col-lg-3'>" + "<div class='note-bg'>" + "<div id='" + theId + "'" + "onclick='deleteNote(this.id)'>" + "<p id='hide-delete' class='glyphicon glyphicon-remove-circle'></p>" + "</div>" + "<div class='noteContent'>" + notesNewArray[i].content + "</div>" + "<div class='noteDate'>" + notesNewArray[i].date + "</div>" + "<div>" + notesNewArray[i].time + "</div>" + "</div>" + "</div>" + "</div>";
}
document.getElementById("results").innerHTML += output;
document.getElementById("msg").innerHTML = ""; //to hide the message for the empty note.
document.getElementById("msgDate").innerHTML = ""; //to hide the message for the empty or wrong date.
document.getElementById("msgTime").innerHTML = ""; //to hide the message for the empty or wrong date.
document.forms['myNotes'].reset(); //reseting the form on saving.
function deleteNote(clickedId) {
var myList = localStorage.myList;
notesArray = JSON.parse(myList);
for (var i = 0; i < notesArray.length; i++) {
if (notesArray[i].id == clickedId) {
notesArray.splice(i, 1); // searching for the same ID number that the user clicked on and deleting it.
}
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
document.getElementById("results").innerHTML = "";
getIt(); // calling again to the notes from the local storage.
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Project</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
</head>
<body id="init">
<div class="center">
<img src="img/title.png" class="img-center" alt="My Task Board" width="876" height="225">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form id="myNotes" name="myNotes">
<div class="form-group">
<textarea rows="8" name="myContent" cols="100" class="form-control" id="content" placeholder="type your note here..." required></textarea><br>
<div><input type="date" class="form-control" id="date" required></div>
<div><input type="time" class="form-control" id="time" required></div>
<input type="submit" class="btn btn-primary" id="save" value="save">
<div id="msg"></div>
<div id="msgDate"></div>
<div id="msgTime"></div>
</div>
</form>
</div>
<div class="col-sm-4"></div>
</div>
</div>
<div id="results" class="singleNote"></div>
<script src="js/myscript.js"></script>
</body>
</html>
thank you.
You can use jquery to solve this problem. For any element that requires to fade in or out you can do this...
$("#div1").fadeIn();
$("#div1").fadeOut();
Here is a link that explains...
Jquery fade in and out
You need to make two async functions fadeIn() and fadeOut() and a function to return a promise.
With async you are solving the function asynchronously meaning other code can continue executing and doesn't have to wait for the return of a priorly called function to start it's execution. Because of this they appear to fade in and out at the same time even though they are called by 4 different lines of code.
Here is a quick example of fade in and fade out done in plain javascript:
(Run the snippet at the bottom of the code)
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fadeIn(elmnt)
{
for(var i=0; i<101; i++)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20); // Play with the sleep time to suit your needs, in miliseconds
}
}
async function fadeOut(elmnt)
{
for(var i=100; i > -1; i--)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20);
}
}
// Simply call the functions anywhere you want like this
fadeIn('fade_1');
fadeIn('fade_2');
fadeOut('fade_3');
fadeOut('fade_4');
.opacityZero
{
opacity:0;
}
.opacityOne
{
opacity:1;
}
.firstDiv
{
position:relative;
float:left;
width:97%;
border:1px solid #000;
padding:5px;
}
.secondDiv
{
position:relative;
float:left;
width:98%;
border:1px solid #000;
padding:5px;
}
.container
{
position:relative;
float:left;
width:95%;
margin-top:20px;
border:1px solid #09f;
padding:10px;
}
h3
{
font-family:calibri;
position:relative;
float:left;
}
<h3>Fade in effect</h3>
<div id="fade_1" class="firstDiv opacityZero">hi</div>
<div class="container">
<span id="fade_2" class="secondDiv opacityZero">hi</span>
</div>
<h3 style="margin:20px 0 0;">Fade out effect</h3>
<div id="fade_3" class="firstDiv opacityOne">hi</div>
<div class="container">
<span id="fade_4" class="secondDiv opacityOne">hi</span>
</div>

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