matching a key from my input field to my json object - javascript

$ (function() {
var heroes = {
"Abaddon":{
"counters": "Undying" + "Anti-Mage" + "Outworld Devourer" + "Shadow Demon" + "Techies" + "Ancient Apparition" + "Meepo" + "Riki"
},
"Alchemist":{
"counters": "Riki" + "Ursa" + "Drow" + "Phantom Assassin" + "Troll Warlord" + "Bounty Hunter" + "Slark" + "Lifestealer"
},
"Ancient Apparition":{
"counters": "Anti-Mage" + "Clinkz" + "Riki" + "Juggernaut" + "Zeus" + "Techies" + "Phantom Assassin" + "Spectre"
},
"Axe":{
"counters": "Timbersaw" + "Venomancer" + "Silencer" + "Necrophos" + "Zeus" + "Phoenix" + "Lich" + "Ancient Apparition"
},
"Bane":{
"counters": "Phantom Lancer" + "Chaos Knight" + "Meepo" + "Tidehunter" + "Sand King" + "Razor" + "Naga Siren" + "Undying"
},
"Batrider":{
"counters": "Huskar" + "Viper" + "Juggernaut" + "Sniper" + "Venomancer" + "Undying" + "Weaver" + "Drow Ranger"
},
"Beastmaster":{
"counters": "Axe" + "Bristleback" + "Lich" + "Timbersaw" + "Zeus" + "Meepo" + "Centaur Warrunner" + "Tidehunter"
},
"Bloodseeker":{
"counters": "Wraith King" + "Techies" + "Tiny" + "Troll Warlod" + "Lifestealer" + "Dragon Knight" + "Legion Commander" + "Chaos Knight"
},
"Bounty Hunter":{
"counters": "Phantom Lancer" + "Slardar" + "Meepo" + "Naga Siren" + "Bloodseeker" + "Chaos Knight" + "Huskar" + "Techies"
},
"Brewmaster":{
"counters": "Undying" + "Omniknight" + "Death Prophet" + "Timbersaw" + "Weaver" + "Techies" + "Queen of Pain" + "Anti-Mage"
},
"Bristleback":{
"counters": "Necrophos" + "Venomancer" + "Viper" + "Ancient Apparition" + "Razor" + "Death Prophet" + "Clockwerk" + "Omniknight"
},
};
var keys = [];
for(var k in heroes) keys.push(k);
$("#searchBar").autocomplete({
source: keys
});
$( "#searchBar" ).autocomplete({ minLength: 2 });
var minLength = $( "#searchBar" ).autocomplete( "option", "minLength" );
$( "#searchBar" ).autocomplete( "option", "minLength", 2 );
$( "#searchBar" ).autocomplete({ autoFocus: true });
$( "#searchBar" ).autocomplete({response: function( event, ui ) {} });
$("#searchBar").bind("keypress", function(e) {
var key = e.keyCode || e.which;
if(key == 13) {
for (var i = 0; i < heroes.length; i++) {
if (document.getElementById("searchBar").value == heroes);
document.getElementById("placeholder").innerHTML = heroes.counters;
};
}
});
});
So basically what I'm trying to build is a counter hero list. what I want to achieve is that when I put a string into the input field (#searchBar) it will run it through my object and see if it matches, it it matches it will return the value(counters, but it's not working.

You are not iterating object fields correctly.
Also I suggest you to use select event of Autocomplete plugin instead of keypress
Here's working code:
$( "#searchBar" ).autocomplete({select: function( event, ui ) {
for (var hero in heroes) {
if (document.getElementById("searchBar").value == hero) {
document.getElementById("placeholder").innerHTML = heroes[hero].counters;
}
};
} });
http://jsfiddle.net/bo1ce55L/2/

Related

How to Add Export button in Jquery Custom Datatable

I am using a Web Template for my web site. I am developing with ASP.NET webform. The data will be shown in a Gridview. The Template also has a custom datatable file but without an Export button. I am sharing the js file here. Can anyone help me to edit the jquery and add the export button (PDF, Excel, and Copy)!
Thanks
(function($) {
'use strict';
$.HSCore.components.HSDatatables = {
/**
*
*
* #var Object _baseConfig
*/
_baseConfig: {
paging: true
},
/**
*
*
* #var jQuery pageCollection
*/
pageCollection: $(),
/**
* Initialization of Datatables wrapper.
*
* #param String selector (optional)
* #param Object config (optional)
*
* #return jQuery pageCollection - collection of initialized items.
*/
init: function(selector, config) {
this.collection = selector && $(selector).length ? $(selector) : $();
if (!$(selector).length) return;
this.config = config && $.isPlainObject(config) ?
$.extend({}, this._baseConfig, config) : this._baseConfig;
this.config.itemSelector = selector;
this.initDatatables();
return this.pageCollection;
},
initDatatables: function() {
//Variables
var $self = this,
config = $self.config,
collection = $self.pageCollection;
//Actions
this.collection.each(function(i, el) {
//Variables
var $this = $(el),
$info = $this.data('dt-info'),
$search = $this.data('dt-search'),
$entries = $this.data('dt-entries'),
$pagination = $this.data('dt-pagination'),
$detailsInvoker = $this.data('dt-details-invoker'),
pageLength = $this.data('dt-page-length'),
isResponsive = Boolean($this.data('dt-is-responsive')),
isSelectable = Boolean($this.data('dt-is-selectable')),
isColumnsSearch = Boolean($this.data('dt-is-columns-search')),
isColumnsSearchTheadAfter = Boolean($this.data('dt-is-columns-search-thead-after')),
isShowPaging = Boolean($this.data('dt-is-show-paging')),
scrollHeight = $this.data('dt-scroll-height'),
paginationClasses = $this.data('dt-pagination-classes'),
paginationItemsClasses = $this.data('dt-pagination-items-classes'),
paginationLinksClasses = $this.data('dt-pagination-links-classes'),
paginationNextClasses = $this.data('dt-pagination-next-classes'),
paginationNextLinkClasses = $this.data('dt-pagination-next-link-classes'),
paginationNextLinkMarkup = $this.data('dt-pagination-next-link-markup'),
paginationPrevClasses = $this.data('dt-pagination-prev-classes'),
paginationPrevLinkClasses = $this.data('dt-pagination-prev-link-classes'),
paginationPrevLinkMarkup = $this.data('dt-pagination-prev-link-markup'),
table = $this.DataTable({
pageLength: pageLength,
responsive: isResponsive,
scrollY: scrollHeight ? scrollHeight : '',
scrollCollapse: scrollHeight ? true : false,
paging: isShowPaging ? isShowPaging : config.paging,
drawCallback: function( settings ) {
var api = this.api(),
info = api.page.info();
$($info).html(
'Showing ' + (info.start + 1) + ' to ' + info.end + ' of ' + info.recordsTotal + ' Entries'
);
}
}),
info = table.page.info(),
paginationMarkup = '';
if (scrollHeight) {
$(table.context[0].nScrollBody).mCustomScrollbar({
scrollbarPosition: 'outside'
});
}
$($search).on('keyup', function() {
table.search(this.value).draw();
});
if(isColumnsSearch == true) {
table.columns().every(function () {
var that = this;
if(isColumnsSearchTheadAfter == true) {
$('.dataTables_scrollFoot').insertAfter('.dataTables_scrollHead');
}
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
$('select', this.footer()).on('change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
}
$($entries).on('change', function() {
var val = $(this).val();
table.page.len(val).draw();
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, val);
}
});
if(isSelectable == true) {
$($this).on('change', 'input', function() {
$(this).parents('tr').toggleClass('checked');
})
}
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, info.pages);
}
// Details
$self.details($this, $detailsInvoker, table);
//Actions
collection = collection.add($this);
});
},
pagination: function(target, table, pagiclasses, pagiitemclasses, pagilinksclasses, paginextclasses, paginextlinkclasses, paginextlinkmarkup, pagiprevclasses, pagiprevlinkclasses, pagiprevlinkmarkup, pages) {
var info = table.page.info(),
paginationMarkup = '';
for (var i = 0; i < info.recordsTotal; i++) {
if (i % info.length == 0) {
paginationMarkup += i / info.length == 0 ? '<li class="' + pagiitemclasses + '"><a id="datatablePaginationPage' + (i / info.length) + '" class="' + pagilinksclasses + ' active" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>' : '<li class="' + pagiitemclasses + '"><a id="' + target + (i / info.length) + '" class="' + pagilinksclasses + '" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>';
}
}
$('#' + target).html(
'<ul class="' + pagiclasses + '">\
<li class="' + pagiprevclasses + '">\
<a id="' + target + 'Prev" class="' + pagiprevlinkclasses + '" href="#!" aria-label="Previous">' + pagiprevlinkmarkup + '</a>\
</li>' +
paginationMarkup +
'<li class="' + paginextclasses + '">\
<a id="' + target + 'Next" class="' + paginextlinkclasses + '" href="#!" aria-label="Next">' + paginextlinkmarkup + '</a>\
</li>\
</ul>'
);
$('#' + target + ' [data-dt-page-to]').on('click', function() {
var $page = $(this).data('dt-page-to'),
info = table.page.info();
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$(this).addClass('active');
table.page($page).draw('page');
});
$('#' + target + 'Next').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('next').draw('page');
if ($currentPage.parent().next().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().next().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
$('#' + target + 'Prev').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('previous').draw('page');
if ($currentPage.parent().prev().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().prev().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
},
format: function(value) {
return value;
},
details: function(el, invoker, table) {
if (!invoker) return;
//Variables
var $self = this;
$(el).on('click', invoker, function() {
var tr = $(this).closest('tr'),
row = table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('opened');
} else {
row.child($self.format(tr.data('details'))).show();
tr.addClass('opened');
}
});
}
};
})(jQuery);

JSON to HTML with jQuery (2 tables from 1 json)

This jQuery code parse json data and create html table to div:
$(document).ready(function () {
const jsonData = $.getJSON("js/quotes.json");
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function () {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && a.$div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 50e3);
});
}),
this._init();
}
quotes("#quotes-block1", $("#quotes-block1").data("quotes1").split(","));
quotes("#quotes-block2", $("#quotes-block2").data("quotes2").split(","));
});
HTML code:
<div id="quotes-block1" data-quotes1="EUR/USD, GBP/USD, USD/CHF, USD/JPY"></div>
<div id="quotes-block2" data-quotes2="XRP/USD, LTC/USD"></div>
Json:
"XRP\/USD": {
"bid": 0.5676,
"ask": 0.5698,
"type": "Cryptos",
"code": "XRP\/USD",
"mid": 0.5687,
"movement": "down",
"spread": 0.0022
},
"LTC\/USD": {
"bid": 82.89,
"ask": 83.72,
"type": "Cryptos",
"code": "LTC\/USD",
"mid": 83.305,
"movement": "down",
"spread": 0.83
},
"ETH\/USD": {
"bid": 588.62,
"ask": 589.63,
"type": "Cryptos",
"code": "ETH\/USD",
"mid": 589.125,
"movement": "up",
"spread": 1.01
},
etc.
I need create table in div id="quotes-block1" and id="quotes-block2", but work only div id="quotes-block2"
What is my mistake? Help!
Live example:
json file: http://maxbeaub.bget.ru/json/js/quotes.json
jquery function: http://maxbeaub.bget.ru/json/js/quotes.js (get data from json and append table to div)
html result: http://maxbeaub.bget.ru/json/json.html (append table only to second div)
The reason being is content being overwritten in second div only get referenced in an a.
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function (div) {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 5e3);
});
}),
this._init(this.$div);

Array is always picking the first value instead of specific value

refreshFileList = function() {
$("#filedetails tr").remove();
for (i = 0, j = fileDetails.length; i < j; ++i) {
$("#filedetails").append("<tr data-filesize='" + fileDetails[i].SIZE + "' data-filename='" + fileDetails[i].KEY + "'><td><strong>" + fileDetails[i].FILENAME + "</strong></td><td class='nodesize'>" + fileDetails[i].SIZE + " MB</td><td>" + fileDetails[i].EXT + "</td>" + fileDetails[i].TAG + "</tr>");
}
},
fileDelete = function(e) {
e.preventDefault();
var parentRow = jQuery(this).closest('tr')
, fileName = fileDetails[i].KEY
, fileSize = fileDetails[i].SIZE;
ajaxFileDelete(fileName, parentRow, fileSize);
},
Into the fileDelete function I don't want to use data-filename and data-filesize but when I am going to use fileName = fileDetails[i].KEY or fileSize = fileDetails[i].SIZE its always deleting the first value of the array instead of specific value but with data-attributes it working as expected.
Add i to the <tr> as a data attribute.
refreshFileList = function() {
$("#filedetails tr").remove();
for (var i = 0, j = fileDetails.length; i < j; ++i) {
$("#filedetails").append("<tr data-index='" + i + "'><td><strong>" + fileDetails[i].FILENAME + "</strong></td><td class='nodesize'>" + fileDetails[i].SIZE + " MB</td><td>" + fileDetails[i].EXT + "</td>" + fileDetails[i].TAG + "</tr>");
}
},
fileDelete = function(e) {
e.preventDefault();
var parentRow = jQuery(this).closest('tr')
, i = parentRow.data('index')
, fileName = fileDetails[i].KEY
, fileSize = fileDetails[i].SIZE;
ajaxFileDelete(fileName, parentRow, fileSize);
},

Problems with remove timestamps in JQuery

When I double click the card the dialog pops up, and it is then possible to create comments. So far so good. When creating the comments it is possible to delete it.
The issue is, that the timestamps can't be removed. The way I'm trying to remove the timestamps is by this line: $('.labelStyle').remove();
I want to be able to remove the timestamps, like the others elements but how?
Live Demo
JQuery: "click" handler
$('#divComments').on('click', '.delete', function (e) {
var uniqueval = $(this).attr("for")
var NameOfDataValue = $('label[for=' + uniqueval + ']').text();
$('img[for=' + uniqueval + ']').remove();
$('label[for=' + uniqueval + ']').remove();
$('p[for=' + uniqueval + ']').remove();
$('.labelStyle').remove();
var arr = $('#divComments').data('comments');
var theIndex = -1;
for (var i = 0; i < arr.length; i++) {
if (arr[i].commentString== NameOfDataValue) {
theIndex = i;
break;
}
}
if (theIndex == -1) {
alert("Error");
}
else {
$('#divComments').data("comments").splice(theIndex, 1);
}
});
JQuery: Add comment function
function addComment(commentString) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var data1 = {
commentString: commentString
};
var div = $('<div />', { class: 'CommentStyle' });
$('<label />', {
id: 'comment' + id,
for: 'comment' + id,
text: commentString
}).on('change', function () {
data1.commentString = $(this).text();
}).appendTo(div);
$('<br/>').appendTo(div);
var $Image = $('<img />',
{
"src": "/Pages/Images/alert.png",
"class": "CommentImage",
"for": "comment" + id
}).appendTo(container);
var d = new Date();
var $fulaDate = $('<div>' + d.getDate()
+ "-" + monthNames[d.getMonth()]
+ "-" + d.getFullYear()
+ "//" + d.getHours()
+ ":" + d.getMinutes()
+ '</div>').addClass('labelStyle').append(' ~').appendTo(div);
var $edit = $('<p />', {
class: 'edit',
for: 'comment' + id,
text: 'Edit'
}).append(' ~').appendTo(div);
var $delete = $('<p />', {
class: 'delete',
for: 'comment' + id,
text: 'Delete'
}).appendTo(div);
div.appendTo(container).focus();
container.data('comments').push(data1);
}
You could do:
$(this).parent().find('.labelStyle').remove();
This will select the parent of the clicked button (.CommentStyle) then find the .labelStyle and remove it.

maintaining a sorted jQuery accordion

I have a situation where I receive certain events over time that each have a timestamp associated with them. I am putting it into a Jquery accordion section that is labelled by date. It works except that I wish to maintain the accordion sections in sorted descending order, i.e most recent date at the top and events belonging to that date go into that section. Here is the complete code I have so far, currently I just append a new date to the end. How do I insert so that it is sorted?
$(function() {
$("#accordion").accordion({
collapsible: true
});
});
function getRandInt(max) {
return Math.floor(Math.random() * Math.floor(max))
}
function getRandomTime() {
var t = ['AM', 'PM']
var hr = getRandInt(13);
var mn = getRandInt(60);
var sec = getRandInt(60);
var ampm = t[Math.floor(Math.random() * 2)]
return (hr + ':' + mn + ':' + sec + " " + ampm);
}
function getRandomDate() {
var month = getRandInt(13);
var day = getRandInt(28);
return ('2018-' + month + '-' + day);
}
function getRandomEvent() {
var events = ['General Event', 'Random', 'Splash', 'Car crash', 'Touchdown', 'Rain', 'Snow'];
var rand = events[Math.floor(Math.random() * events.length)];
return rand;
}
function getRandomSection(sections) {
var rand = sections[Math.floor(Math.random() * sections.length)];
return rand;
}
function getPopupDivId(t, e, d) {
var popup_div_str = t + e;
var popup_div_id = popup_div_str.replace(/\s{1,}/g, "");
popup_div_id = popup_div_id.replace(/:/g, "");
return popup_div_id;
}
function getDescriptiveDate(dateStr) {
var d_t = dateStr.split("T");
var timeStr = d_t[0] + " " + d_t[1];
console.log(timeStr);
var date = new Date(timeStr + ' UTC');
return "Event time: " + date.toString()
}
function makeTable(eventDetails) {
var d = getDescriptiveDate("2018-11-07T00:49:05");
var popupStr = d + '<br>' + '<table border="1"><tr><th>Parameter Name</th><th>Value</th></tr>';
var data = JSON.parse(eventDetails);
var startTag = '<tr><td>';
var endTag = '</td>';
var rowEnd = '</tr>'
for (var key in data) {
popupStr += (startTag + key + endTag + '<td>' + data[key] + endTag + rowEnd);
}
return popupStr + '</table>';
}
var currentDialog = '';
function setPopupDiv(t, e, d, popup_div_id) {
var table = makeTable('{"Temp": 24, "WindChill": "14", "Dew point": 10}');
var popup_div = '<div id="dialog' + popup_div_id + '\" ' + 'style="display:none">' + table + '</div>';
console.log("setPopupDiv: popup div: " + popup_div);
$('.' + d).append(popup_div);
$('#' + popup_div_id).click(function() {
$(function() {
if (currentDialog == '') {
currentDialog = "#dialog" + popup_div_id;
} else {
console.log('closing dialog' + currentDialog);
$(currentDialog).dialog('close');
currentDialog = "#dialog" + popup_div_id;
}
$("#dialog" + popup_div_id).dialog();
$("#dialog" + popup_div_id).dialog('open');
});
console.log("dialog link click");
return false;
});
}
/* "Create new accordion" button handler */
function addData() {
var d = getRandomDate();
var e = getRandomEvent();
var t = getRandomTime();
var popup_div_id = getPopupDivId(t, e, d);
var ev = '' + t + ' ' + '' + e;
var section = '<h3>' + d + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + d + '\">' + '<li>' + ev + '</li></ul>' + '</div>';
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(t, e, d, popup_div_id);
console.log("addData(): " + dom_element);
var e2 = getRandomEvent();
var t2 = getRandomTime();
popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>';
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataActual(eventDate, eventTime, eventType) {
var popup_div_id = getPopupDivId(eventTime, eventType, eventDate);
var evt = '' + eventTime + ' ' + '' + eventType;
var section = '<h3>' + eventDate + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + eventDate + '\">' + '<li>' + evt + '</li></ul>' + '</div>';
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
if (this.className == eventDate) {
return this.className;
}
}
}
}).get();
if (arrayOfClassNames.length == 0) {
/* New section */
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(eventTime, eventType, eventDate, popup_div_id);
console.log(dom_element);
} else {
/* Exists already*/
d = arrayOfClassNames[0];
popup_div_id = getPopupDivId(eventTime, eventType, d);
var eventToAppend = '<li>' + '' + eventTime + ' ' + '' + eventType + '</li>';
$('.' + d).append(eventToAppend);
setPopupDiv(eventTime, eventType, d, popup_div_id);
}
}
function addDataOrNew() {
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
var toss = getRandInt(2);
if (toss == 0) {
var d = getRandomSection(arrayOfClassNames);
console.log("toss returned 0, adding to existing section " + d);
console.log("Chosen one to add to:" + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
} else {
var d = getRandomDate();
console.log("toss returned 1, adding a new section " + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
}
}
function addDataToRandomSection() {
var e = getRandomEvent();
var t = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
console.log(arrayOfClassNames);
d = getRandomSection(arrayOfClassNames);
console.log("Chosen one:" + d);
var e2 = getRandomEvent();
var t2 = getRandomTime();
var popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataToTopSection() {
var e2 = getRandomEvent();
var t2 = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
d = arrayOfClassNames[0];
var popup_div_id = getPopupDivId(t2, e2, d);
setPopupDiv(t2, e2, d, popup_div_id);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href='https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css' rel='stylesheet'>
<!doctype html>
<button onclick="addData()" class="regular">Create new Accordion</button>
<button onclick="addDataToRandomSection()" class="regular">Add data to random section</button>
<button onclick="addDataOrNew()" class="regular">Add new section or append to existing</button>
<fieldset id="patient-event-list">
<legend>Event History</legend>
<div id="eventinfo-body">
<button type="button" id="more" onclick="addDataToTopSection()">More history</button>
</div>
<div id="accordion" class="accordion">
</div>
</fieldset>

Categories

Resources