I have a simple drag and drop system when an item is entered, it creates a localstorage object with the "value" key. If I replace this added item with the drag and drop event, a new localstorage element is created with the "other" key and it is saved there, but I want it to be deleted from the "value" section when the item is replaced. How can I achieve this? You can check the codepen demo for a trial. Codepen: https://codepen.io/BerkayAkgurgen/pen/ExNbZGo
// Above Code is only about localstorage full code is on codepen account
function getLocalStorage() {
let value;
if (localStorage.getItem('value') === null) {
value = [];
} else {
value = JSON.parse(localStorage.getItem("value"))
}
return value;
}
function addToLocalStorage(paragraph) {
let value = getLocalStorage();
value.push(paragraph);
localStorage.setItem("value", JSON.stringify(value))
}
function changeAddToStorage(value) {
localStorage.setItem("other", JSON.stringify(value))
}
function dragStart(element) {
element.classList.add('draggable')
}
function dragEnd(element) {
drags.forEach(function (item) {
if (item.classList.contains('box-2')) {
changeAddToStorage(element.innerHTML)
}
})
element.classList.remove('draggable')
}
To remove the item from "value", call localStorage.removeItem("value") when the item is replaced.
function changeAddToStorage(value) {
localStorage.removeItem("value") // remove "value"
localStorage.setItem("other", JSON.stringify(value)) // save in "other"
}
Related
I am trying to add a line to a Sales Oder when a specific item has been added, but before it does, I need it to verify the state first.
This is where my struggle comes in. I have the code to add the item correctly working, but my state check errors out.
function validateField(type, name, linenumber) {
var shipstate = nlapiGetFieldText()
if (shipstate == 'PA') {
function recalc(type) {
if (type == 'item') {
var itemId = nlapiGetCurrentLineItemValue('item', 'item');
if (itemId == 1658) {
//Insert item
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 1516);
nlapiSetCurrentLineItemValue('item', 'quantity', 1);
nlapiSetCurrentLineItemValue('item', 'amount', '0.24');
nlapiCommitLineItem('item');
}
}
return true;
}
}
return true;
}
Any insight to where my issue is? I think my issue is where I'm storing the state value so it can check the variable.
I would recommend adding your line with a recalc function instead of a validateField function. This is because if you try to add a new line while you are still editing an existing line it will cancel out of your current line. With a recalc function it will wait until you hit the 'Add' button on the existing line before checking the state and adding a new line.
You are on the right track with your state validation, the function you need is nlapiGetFieldValue('shipstate');. I believe the code below should solve your issue.
function recalc(type) {
var shipstate = nlapiGetFieldValue('shipstate');
if (shipstate === 'PA') {
addNewLine(type);
}
return true;
}
function addNewLine(type) {
if (type === 'item') {
var itemId = nlapiGetCurrentLineItemValue('item', 'item');
if (itemId === '1658') {
//Insert item
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', '1516');
nlapiSetCurrentLineItemValue('item', 'quantity', '1');
nlapiSetCurrentLineItemValue('item', 'amount', '0.24');
nlapiCommitLineItem('item');
}
}
return true;
}
I am using the below code to render the same as many as times,
I have two sections, one section with show-all class and another with no class.
When 'show-all' class is not available, it need to run countIncrease function, if class available no need to run the function,
In every time section need to check whether the class is available or not.
class Grid {
init() {
$('.grid').each(function() {
const $this = $(this);
// getting values & url from from html
const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
const hasClass = $this.find('.grid').hasClass('grid_showall');
// countIncrease shows the inital 6 compoents/div and rest of will be hidden
// onclick it will display 3 components/div
function countIncrease() {
let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
$this.find(`.grid__content > .grid__component:gt(' ${limit - 1} ') `).hide();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
else {
$this.find('.grid__cta').show();
}
$this.find('.grid__cta').on('click', function(event) {
event.preventDefault();
limit += incrementalCall;
$this.find(`.grid__content > .grid__component:lt(' ${limit} ')`).show();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
});
}
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
// on dropdown change taking the selected dropdown value and adding #end of the url and replacing the previous html
$this.find('.grid__dropdown-select').on('change', function() {
const optionValue = this.value;
$.ajax({
url: dropDownUrlpath + optionValue,
success(result) {
$this.find('.grid__content').html(result);
countIncrease();
}
});
});
});
}
}
I written if condition, but it running once and giving false condition in both the scenarios,
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
How to handle it...?
shouldnt you add a parameter to the .hasClass so it knows what to check?
if ( $this.hasClass ('some class') === true ) {
alert('something');
}
or set if(hasClass.length > 0){}
keep the checking class in a variable by finding with parent div,
const hasClass = $this.find('.grid').hasClass('grid_showall');
gets the attribute value for only the first element in the matched set with .attr() method
const classInthis = hasClass.attr('class');
check the condition, with
if (classInthis !== 'grid_showall') {
countIncrease();
}
I'm having troubles with setting default category to this script. I want by default to be listed only Category 1 with one news in it insead of All but nothing I tried seem to work. Any ideas?
This is the full code with HTML and some CSS: https://codepen.io/NickyCDK/pen/lhaiz
//Filter News
$('select#sort-news').change(function() {
var filter = $(this).val()
filterList(filter);
});
//News filter function
function filterList(value) {
var list = $(".news-list .news-item");
$(list).fadeOut("fast");
if (value == "All") {
$(".news-list").find("article").each(function (i) {
$(this).delay(200).slideDown("fast");
});
} else {
//Notice this *=" <- This means that if the data-category contains multiple options, it will find them
//Ex: data-category="Cat1, Cat2"
$(".news-list").find("article[data-category*=" + value + "]").each(function (i) {
$(this).delay(200).slideDown("fast");
});
}
}
You could use a trigger
$('select#sort-news').trigger(filterList('Cat1'), 'click');
I have a multiselect with many options. When 'everybody' is selected it removes other selected, if other are selected and the 'everybody' is selected it should remove it.
To remove the other and keep the item 'everybody' it's ok. But I have problem to keep other and only remove everybody.
For the moment I have something like :
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
var idToRemove = 0;
groupIdsData = $('#scheduled_publication_groups_ids').select2('data');
groupIdsData.forEach(function(e, i) {
if (e.text === 'everybody') {
idToRemove = i;
}
});
groupIdsData.splice(idToRemove, 1);
$('#scheduled_publication_groups_ids').select2({'data': groupIdsData}).trigger("change");
}
}
});
},
With this code groupIdsData is tonly the selected elements I want (all expect everybody's group). But after I'm stuck to change the view. select2({'data': groupIdsData}) doesn't seems to be the right choice.
Few things :
I don't think I'm setting the idToRemove properly
What the best way to update the value of the select2 multiselect? It seems it can be a hash
The answer is to use select2('val') to get a array of ids, and then work with this. Code is better using .val() not full select2 objects.
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
groupIds = $('#scheduled_publication_groups_ids').select2('val');
groupToKeep = groupIds.splice( $.inArray(group_everybody_id, groupIds), 1);
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(groupToKeep).trigger("change");
}
}
});
},
I have a checkbox whose value $row['uid'] I would like to store in local storage using javascript or jquery. When the user "unchecks" the checkbox, the value should be removed from local storage
This is my html:
<form> Favorites <input type="checkbox" class="favorite" value="'.$row['uid'].' onclick='.fave.add();'"></form>
This is what I have for the local storage in javascript at the moment. I'm not quite sure how I should add and remove the value $row['uid']
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
$(function () {
var data = localStorage.getItem("favorite");
if (data !== null) {
$("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("favorite", $(this).val());
}
else {
localStorage.removeItem("favorite");
}
});
Any and all help is much appreciated!
localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do localStorage.setItem("checkbox_value", true) and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so: $(checkbox).is(':checked') and use a simple if-else clause to pass in true or false. then when you reload your page, on $( document ).ready() you can get the values using localStorage.getItem(key) and use Javascript to set the check boxes values.
This is how i would go about using localStorage to remember check box values.
Hope i helped! Ask me if anything is unclear.
Here's an example to get you headed in the right direction:
var boxes, arr;
// This function loads the array and then checks the uid of each checkbox
// against it.
function checkBoxes() {
arr = loadBoxArray();
$.each($('input[type=checkbox]'), function (i, el) {
if (arr.indexOf(i) > -1) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
}
// If the localStorage item is available, load it into an array
// otherwise set a default array and save it to localStorage
function loadBoxArray() {
if (localStorage.getItem('boxes')) {
arr = loadBoxArray();
} else {
arr = [0, 2];
saveBoxArray(arr);
}
}
// Save the array to localStorage
function saveBoxArray(arr) {
localStorage.setItem('boxes', JSON.stringify(arr));
}
// On page load check the boxes found in localStorage
checkBoxes();
// Clicking a checkbox will update the checkbox array which is then saved to localStorage
$('input[type=checkbox]').click(function () {
var arr = $.map($('input[type=checkbox]:checked'), function (el) {
return $(el).data('uid');
});
saveBoxArray(arr);
});
If you want the check box state to persist after page refresh and if you don't mind using jQuery:
http://jsfiddle.net/9L2Ac/
$(function () {
var data = localStorage.getItem("favorite");
if (data !== null) {
$("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("favorite", $(this).val());
} else {
localStorage.removeItem("favorite");
}
});