hope you can help!
I am working on a school assignment with local storage and drag & drop, so I am very new to this. I'm making a kind of task manager, similar to Trello, with tasks, members and different lists.
The problem I am having is that the things I drag are "reset" if I refresh the page. How can I fix it so it stays where I drop it?
Here the tasks are created:
function renderTasks() {
var outputTask = JSON.parse(window.localStorage.getItem("outputTask")) || [];
var outputTaskEl = document.getElementById("outputTasks");
outputTaskEl.innerHTML = "";
for (var product of outputTask) {
var productTwo = document.createElement("div");
productTwo.setAttribute('class', 'task');
productTwo.setAttribute('draggable', true);
var {task,member,deadline} = product;
productTwo.innerHTML =
"<div id='task'>" +
"<p>" + product.task + "</p>" +
"<ul>" +
"<li><img id='pencil-img' src='images/pencil.png' alt='task-options. Pencil'>"+
"<ul class='dropdown-menu'>" +
"<li><a href='#' onclick='deleteTask(" + product.id + ")'>Delete task</a></li>" +
"<li><a href='#' onclick='editTask(" + product.id + ")'>Edit task</a></li>" +
"</ul>"
"</li>" +
"</ul>";
outputTaskEl.appendChild(productTwo);
}
for ( i = 0; i < outputTask.length; i++){
var taskId = document.getElementsByClassName("task");
taskId[i].id = "task" + (i + 1);
}
}
And this is the drag and drop code:
function dragDropItems() {
const taskItems = document.querySelectorAll('.task');
const taskFields = document.querySelectorAll('.taskField');
for (let i = 0; i < taskItems.length; i++) {
const item = taskItems[i];
item.addEventListener('dragstart', function () {
draggedItem = item;
setTimeout(function () {
}, 0)
});
item.addEventListener('dragend', function () {
setTimeout(function () {}, 0);
})
for (let j = 0; j < taskFields.length; j ++) {
const list = taskFields[j];
draggedItem = item;
list.addEventListener('dragover', function (e) {
e.preventDefault();
});
list.addEventListener('dragenter', function (e) {
e.preventDefault();
});
list.addEventListener('drop', function (e) {
e.preventDefault();
this.append(draggedItem);
});
}
}
}
Try this:
// Save object
localStorage.setItem('key', JSON.stringify(obj))
// Get object
let obj = JSON.parse(localStorage.getItem('key'))
Related
I have created my table with jQuery and have it using filtering on the column. However, ran into something interesting.
Below is my fiddle
https://jsfiddle.net/4sy5dweg/1/
So my issue is as follows -
Once I find what I am looking for by filtering. If I decided to start backspacing I want it to continue searching that column and obviously start going backwards on searching.
I hope that makes sense.
$.extend($.expr[":"], {
"containsIN": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$("[id*=TXTSEARCH]").keyup(function () {
tablename = $(this).closest('table').attr('id');
mytd = $(this).closest('th');
var indexColumn = mytd.index();
var data = this.value.toLowerCase().split(" ");
var jo = $("[id*=" + tablename + "]").find("tr:not(:first)");
jo.filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
console.log(data[d]);
return true;
}
}
return false;
}).hide();
})
I know the issue has to do with hiding that row on initial search. However, somehow for isntance if someone has a typo and goes to backspace it wont show anything because that row is still hidden. Is there a way to keep the other filters in place and basically remove the filter from the row being corrected?
I hope I am making sense.
Update I have attempted the following -
$("[id*=TXTSEARCH]").keyup(function () {
var tablename = $(this).closest('table').attr('id');
console.log(tablename);
var FindMyRow;
$("#" + tablename).find('th:visible').find($("[id*=TXTSEARCH]")).each(function () {
FindMyRow = $(this).closest('th:visible');
var indexColumn = FindMyRow.index();
console.log($(this).attr('id') + " " + indexColumn);
var data = this.value.toLowerCase().split(" ");
var jo = $("[id*=" + tablename + "]").find("tr:not(:first)");
jo.show().filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
console.log(data[d]);
return true;
}
}
return false;
}).hide();
});
to no avail.
Decided to change my way of doing it.
I added a button to each column header that the user can click on so that if they make a type they just check it before clicking it.
$("[id*=BTNSEARCH]").click(function (e) {
e.preventDefault();
var tablename = $(this).closest('table').attr('id');
mytd = $(this).closest('th');
var TextBoxToSearch = ($(this).prev('input').val());
var indexColumn = mytd.index();
FindMyRow = $(this).closest('th:visible');
var indexColumn = FindMyRow.index();
var data = TextBoxToSearch.toLowerCase().split(" ");
var jo = $("#" + tablename).find("tr:not(:first)");
jo.filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
return true;
}
}
return false;
}).hide();
})
I have created an accordion with categories. I am pulling the content from a share point list with an ajax call. Each item on the share point list has its category assigned (automotive, entertainment, housing, etc). I need every item to be filtered by category.
https://jsfiddle.net/angelogianopulos/7L392emj/11/
$(document).ready(function() {
/*r container = document.createElement("div");
container.setAttribute('id', 'container');
container.classList.add('container', 'text-center', 'my-5');*/
$.ajax({
url: "http://bc-net/_api/web/lists/GetByTitle('specialDiscounts')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
var createRows = function(i, items) {
//Creates 3 Rows inside container
var row = document.createElement("div");
row.setAttribute('id', 'row' + i);
row.classList.add('row', 'animated', 'fadeInUp');
//Appends Row to Container
var getContainer = document.getElementById('automotive');
getContainer.appendChild(row);
createColumns(i, items);
}; //End of creare Rows Function
//Creates columns
var createColumns = function(i, items) {
for (var j = i; j < (i + 3); j++) {
//Creates 3 Columns inside the 3 rows
var columns = document.createElement("div");
columns.setAttribute('id', 'columns' + j);
columns.classList.add('col-md-4');
//appends the 3 columns inside the rows
var getRow = document.getElementById('row' + i);
getRow.appendChild(columns);
//Create single News
var singleNews = document.createElement("div");
singleNews.setAttribute('id', 'singleNews' + j);
singleNews.classList.add("single-news", "mb-4");
var getColumns = document.getElementById('columns' + j);
getColumns.appendChild(singleNews);
//Inside Row
var insideRow = document.createElement("div");
insideRow.setAttribute('id', 'insideRow' + j);
insideRow.classList.add('row');
var getsingleNews = document.getElementById('singleNews' + j);
getsingleNews.appendChild(insideRow);
//Col-md-3
var insideCol = document.createElement("div");
insideCol.setAttribute('id', 'insideCol' + j);
insideCol.classList.add('col-md-3');
//Col-md-9
var insideColRight = document.createElement("div");
insideColRight.setAttribute('id', 'insideColRight' + j);
insideColRight.classList.add('col-md-9');
var getInsideRow = document.getElementById('insideRow' + j);
getInsideRow.appendChild(insideCol);
getInsideRow.appendChild(insideColRight);
//Rounded Image Class
var rounded = document.createElement("div");
rounded.setAttribute('id', 'rounded' + j);
rounded.classList.add('rounded', 'z-depth-1', 'mb-4');
var getinsideCol = document.getElementById('insideCol' + j);
getinsideCol.appendChild(rounded);
//Pulls the images from the list
var image = document.createElement("img");
image.setAttribute('id', 'image' + j);
image.classList.add("img-fluid");
image.src = items[j].Image.Url;
var getRounded = document.getElementById('rounded' + j);
getRounded.appendChild(image);
//Pulls header from the list
var title = document.createElement("p");
title.setAttribute('id', 'title' + j);
title.innerHTML = items[j].Title;
title.classList.add("font-weight-bold", "dark-grey-text");
insideColRight.appendChild(title);
var justifyContent = document.createElement('div');
justifyContent.setAttribute('id', 'justifyContent' + j);
justifyContent.classList.add('d-flex', 'justify-content-between', 'topSpace');
insideColRight.appendChild(justifyContent);
var textTruncate = document.createElement('div');
textTruncate.setAttribute('id', 'textTruncate' + j);
textTruncate.classList.add('col-11', 'text-truncate', 'pl-0', 'mb-3');
justifyContent.appendChild(textTruncate);
//Pulls anchor from the list
var anchor = document.createElement("a");
anchor.setAttribute('id', 'anchor' + j);
anchor.setAttribute('href', items[j].Link.Url, +j);
anchor.setAttribute('target', '_blank', +j);
anchor.classList.add("dark-grey-text");
anchor.innerHTML = items[j].Description;
textTruncate.appendChild(anchor);
var arrowAnchor = document.createElement("a");
arrowAnchor.setAttribute('id', 'arrowAnchor' + j);
arrowAnchor.setAttribute('target', '_blank' + j);
arrowAnchor.setAttribute('href', items[j].Link.Url, +j);
justifyContent.appendChild(arrowAnchor);
var iconArrow = document.createElement('i');
iconArrow.classList.add('fas', 'fa-angle-double-right');
var getarrowAnchor = document.getElementById('arrowAnchor' + j);
getarrowAnchor.appendChild(iconArrow);
//var test = document.getElementById( 'arrowAnchor' + j);
//test.onclick = function() {
// console.log('Hello');
//}
} //End of j Loop
return;
} // End of createColumns function
//Array of categories
var catGroup = [];
console.log(catGroup);
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
var categories = items[i].Category;
console.log(categories)
catGroup.push(categories);
if (catGroup[i] === "Automotive") {
var automotive = document.getElementById('automotive');
console.log(catGroup[i]);
}
if (catGroup[i] === "Entertainment") {
var entertainment = document.getElementById('entertainment');
console.log(catGroup[i]);
}
if (catGroup[i] === "Health and Beauty") {
var health = document.getElementById('health');
console.log(catGroup[i]);
}
if (catGroup[i] === "Travel") {
var travel = document.getElementById('travel');
console.log(catGroup[i]);
}
if (catGroup[i] === "Electronics") {
var electronics = document.getElementById('electronics');
console.log(catGroup[i]);
}
if (catGroup[i] === "Services") {
var services = document.getElementById('services');
console.log(catGroup[i]);
}
if (catGroup[i] === "Housing") {
var housing = document.getElementById('housing');
console.log(catGroup[i]);
} else {}
if (i % 3 == 0) {
createRows(i, items);
} //end of % if statement
} //End of for loop
} //End of if item.length statement
},
error: function(data) {
alert("Error: " + data);
}
}); //End Service Icons //End Service Icons
}); //End ready function
I expect every item to be placed by category in its own content panelenter image description here
After looking into your question, what I understood is you just want to filter your data on the basis of 'category assigned'.
I will refer you to use JavaScript Filter like so:
const result = items.filter(Category => Category === "Automotive" );
Or, if you can use Lodash, there are a lot of ways to filter and even you can group by the Category.
You can check out here for Lodash:
Documentation Lodash
If I misunderstood your question, please let me know so I can edit my answer.
So I have a select element and I am appending the data I am getting back from my API.
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1) {
$.getJSON("http://localhost:9000/api/helmets", function (key, value) {
console.log("request helmets");
var item = "";
headitemData = key;
var len = key.length;
for (let i = 0; i < len; i++) {
item += '<option value="' + key + '">' + key[i].Name + '</option>';
}
$('#itemSelect').append(item);
});
}
else {
clearIndex(headitemData);
}
}
That right there returns this
Which is just what I want.
But if I want to get other data like.. the Icon
Let's say I want to log to the console when I select a item from the Select element, how would I do that?
The end goal is to print out the Icon property of the json object when I change item in the Select.
JsonData example
<ItemModel>
<ACrush>+0</ACrush>
<AMagic>-5</AMagic>
<ARange>-2</ARange>
<ASlash>+0</ASlash>
<AStab>+0</AStab>
<DCrush>+43</DCrush>
<DMagic>-3</DMagic>
<DRange>+48</DRange>
<DSlash>+49</DSlash>
<DStab>+47</DStab>
<Icon>
https://vignette.wikia.nocookie.net/2007scape/images/a/a0/3rd_age_full_helmet.png/revision/latest?cb=20141217224936
</Icon>
<MagicDamage>+0%</MagicDamage>
<MeleeStrength>+0</MeleeStrength>
<Name>3rd age full helmet</Name>
<Prayer>+0</Prayer>
<RangedStrength>+0</RangedStrength>
<Slayer>0</Slayer>
<Undead>0</Undead>
</ItemModel>
You can set a data for your option like:
'<option data-icon="'+ key[i].Icon +'"></option>'
And then you can bind a change for your select after create your list:
$('select').on('change', function () {
const _this = $(this).find(':selected');
const icon = _this.attr('data-icon');
console.log(icon);
})
Since you want to use the data in other areas of your code, use a closure to create an environment where your variables don't leak out into the global space. For example, with the callback:
(function () {
var myData;
function test(callback) {
$.getJSON("http://localhost:9000/api/helmets",function (data) {
callback(data);
});
}
test(function (data) {
myData = data;
});
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1){
console.log("request helmets");
var item = "";
headitemData = myData;
var len = myData.length;
for (let i = 0; i < len; i++) {
item += '<option value="' +myData+ '">' + myData[i].Name + '</option>';
}
$('#itemSelect').append(item);
}
else {
clearIndex(headitemData);
}
}
$("#itemSelect").on("change",function(){
var value = $(this).val();
var newData = myData.filter(item=>{
if(myData.Name==value){
return item;
}
});
console.log(newData.Icon);
});
myData is cached as a global variable specific to that closure. Note the other functions will only be able to use that variable once the callback has completed.
Modified version below:
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1) {
$.getJSON("http://localhost:9000/api/helmets", function (key, value) {
console.log("request helmets");
var item = "";
headitemData = key;
var len = key.length;
for (let i = 0; i < len; i++) {
var icon=key[i].Icon;
item += '<option data-icon="'+icon+'" value="' + key + '">' + key[i].Name + '</option>';
}
$('#itemSelect').append(item);
});
}
else {
clearIndex(headitemData);
}
}
Simple test to get the Icon from the first option in select:
//Get first option to test output
var test=$("#itemselect option:first");
//Read data-icon
console.log(test.data('icon'));
//To update data-icon
test.data('icon','new icon');
To echo when select is changed
$("#itemselect").change(function(e) {
var optionSelected = $("option:selected", this);
console.log (optionSelected.data('icon'));
});
I have a JQuery plugin i am using as part of my project. The file is located in the root of my solution folder under a file called "jquery.tablePagination.js" I want to alter some of the parameters inside of the file without hard coding the data.
The script is as follows..
(function ($) {
$.fn.tablePagination = function (settings) {
var defaults = {
firstArrow: (new Image()).src = "./images/first.gif",
prevArrow: (new Image()).src = "./images/prev.gif",
lastArrow: (new Image()).src = "./images/last.gif",
nextArrow: (new Image()).src = "./images/next.gif",
rowsPerPage: 5,
currPage: 1,
optionsForRows: [5, 10],
ignoreRows: []
};
settings = $.extend(defaults, settings);
return this.each(function () {
var table = $(this)[0];
var totalPagesId = '#' + table.id + '+#tablePagination #tablePagination_totalPages';
var currPageId = '#' + table.id + '+#tablePagination #tablePagination_currPage';
var rowsPerPageId = '#' + table.id + '+#tablePagination #tablePagination_rowsPerPage';
var firstPageId = '#' + table.id + '+#tablePagination #tablePagination_firstPage';
var prevPageId = '#' + table.id + '+#tablePagination #tablePagination_prevPage';
var nextPageId = '#' + table.id + '+#tablePagination #tablePagination_nextPage';
var lastPageId = '#' + table.id + '+#tablePagination #tablePagination_lastPage';
var possibleTableRows = $.makeArray($('tbody tr', table));
var tableRows = $.grep(possibleTableRows, function (value, index) {
return ($.inArray(value, defaults.ignoreRows) == -1);
}, false)
var numRows = tableRows.length
var totalPages = resetTotalPages();
var currPageNumber = (defaults.currPage > totalPages) ? 1 : defaults.currPage;
if ($.inArray(defaults.rowsPerPage, defaults.optionsForRows) == -1)
defaults.optionsForRows.push(defaults.rowsPerPage);
function hideOtherPages(pageNum) {
if (pageNum == 0 || pageNum > totalPages)
return;
var startIndex = (pageNum - 1) * defaults.rowsPerPage;
var endIndex = (startIndex + defaults.rowsPerPage - 1);
$(tableRows).show();
for (var i = 0; i < tableRows.length; i++) {
if (i < startIndex || i > endIndex) {
$(tableRows[i]).hide()
}
}
}
function resetTotalPages() {
var preTotalPages = Math.round(numRows / defaults.rowsPerPage);
var totalPages = (preTotalPages * defaults.rowsPerPage < numRows) ? preTotalPages + 1 : preTotalPages;
if ($(totalPagesId).length > 0)
$(totalPagesId).html(totalPages);
return totalPages;
}
function resetCurrentPage(currPageNum) {
if (currPageNum < 1 || currPageNum > totalPages)
return;
currPageNumber = currPageNum;
hideOtherPages(currPageNumber);
$(currPageId).val(currPageNumber)
}
function resetPerPageValues() {
var isRowsPerPageMatched = false;
var optsPerPage = defaults.optionsForRows;
optsPerPage.sort();
var perPageDropdown = $(rowsPerPageId)[0];
perPageDropdown.length = 0;
for (var i = 0; i < optsPerPage.length; i++) {
if (optsPerPage[i] == defaults.rowsPerPage) {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i], true, true);
isRowsPerPageMatched = true;
}
else {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i]);
}
}
if (!isRowsPerPageMatched) {
defaults.optionsForRows == optsPerPage[0];
}
}
function createPaginationElements() {
var htmlBuffer = [];
htmlBuffer.push("<div id='tablePagination'>");
htmlBuffer.push("<span id='tablePagination_perPage'>");
htmlBuffer.push("<select id='tablePagination_rowsPerPage'><option value='5'>5</option></select>");
htmlBuffer.push("per page");
htmlBuffer.push("</span>");
htmlBuffer.push("<span id='tablePagination_paginater'>");
htmlBuffer.push("<img id='tablePagination_firstPage' src='" + defaults.firstArrow + "'>");
htmlBuffer.push("<img id='tablePagination_prevPage' src='" + defaults.prevArrow + "'>");
htmlBuffer.push("Page");
htmlBuffer.push("<input id='tablePagination_currPage' type='input' value='" + currPageNumber + "' size='1'>");
htmlBuffer.push("of <span id='tablePagination_totalPages'>" + totalPages + "</span>");
htmlBuffer.push("<img id='tablePagination_nextPage' src='" + defaults.nextArrow + "'>");
htmlBuffer.push("<img id='tablePagination_lastPage' src='" + defaults.lastArrow + "'>");
htmlBuffer.push("</span>");
htmlBuffer.push("</div>");
return htmlBuffer.join("").toString();
}
if ($(totalPagesId).length == 0) {
$(this).after(createPaginationElements());
}
else {
$('#tablePagination_currPage').val(currPageNumber);
}
resetPerPageValues();
hideOtherPages(currPageNumber);
$(firstPageId).bind('click', function (e) {
resetCurrentPage(1)
});
$(prevPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber - 1)
});
$(nextPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber + 1)
});
$(lastPageId).bind('click', function (e) {
resetCurrentPage(totalPages)
});
$(currPageId).bind('change', function (e) {
resetCurrentPage(this.value)
});
$(rowsPerPageId).bind('change', function (e) {
defaults.rowsPerPage = parseInt(this.value, 10);
totalPages = resetTotalPages();
resetCurrentPage(1)
});
})
};
})(jQuery);
I want to be able to alter the following settings: RowsPerPage and OptionforRows.
I have tried to copy and paste the code from the script directly into my .aspx file next to some other Jquery/JavaScript I already have however the plugin doesn't run when I do this.
Could it be possible to write to the settings part of the file from the code behind? It would also work if the file could read the settings from a certain hidden field but I can't get it to run on my .aspx to do this. I'm not sure how to go about solving this issue.
I have ended up solving this issue by first copying the script and pasting in my .aspx file. I was originally copying the code inside of the document ready function:
$(document).ready(function)
Once I have had this done It was quite easy to pass through a variable from the code behind to be used as the required setting.
rowsPerPage: <%=PageRowAmount%>,
For the code behind I have added the following:
Public PageRowAmount As Integer = 10
and in the page_load I have added
Page.DataBind()
Solved!
var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}