How to store jQuery objects locally using localStorage? - javascript

I'm trying to build a to-do list app (beginner here), and have some difficulties in storing the values inputted so that I can store this locally, so once the page is reloaded, it's still saved. You input an item and it gets stored in task, and then it's checked if it's deleted or checked-off, and I think appended to an array, so I'm not sure if I should be iterating over this. Here is the code: (Thank you in advance!)
$(".txtb1").on("keyup", function (e) {
console.log("sdfsdfsd");
//13 means enter button
if (e.keyCode === 13 && $(".txtb1").val() != "") {
console.log("entered");
var task = $("<div class='task'></div>").text($(".txtb1").val());
var del = $("<i class='fas fa-trash-alt'></i>").click(function () {
var p = $(this).parent();
p.fadeOut(function () {
p.remove();
});
});
var check = $("<i class='fas fa-check'></i>").click(function () {
var p = $(this).parent();
p.fadeOut(function () {
$("#task2.comp").append(p);
/* No stupid appendChild */
p.fadeIn();
});
$(this).remove();
});
task.append(del, check);
$("#task1.notcomp").append(task);
//to clear the input
$(".txtb1").val("");
//task needs to be set
localStorage.setItem('task', task.text());
var data = localStorage.getItem('task');
localStorage.removeItem('$task');
/* ------------------------ */
//Other option: Store data
localStorage.setItem('task1', JSON.stringify(task));
//Get data
var data = JSON.parse(localStorage.getItem('task1'));
//Remove data
localStorage.removeItem('task1');
}
}

Related

Java Script function link combine issue in my case

I have issue in flask project, i need set up two js with one link if both was clicked or checked.
For example my data table do changes if clicked check box or selected from multi select some options.
But need make them both if selected and clicked (can be only selected or only just clicked). But need make and option for both
For make issue more clearly after get checked send value in the python function.
I think problem with url.
My js code.
// MULTISELECT
$('.selectpicker').on('change', function() {
selectedServices = $(this).val();
alert(selectedServices)
var url = '/api/VERSION/DATABALE/get?groupFilter='+ selectedServices
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
// CHECK BOX
$('input[name="checkboxGroup1"]').on("click", function(){
console.log("Filter clicked")
var own = false;
var own = false;
// var id = parseInt($(this).val(), 10);
if($('#own').is(":checked")) { var f_own = true;}
else { var f_own = false; }
if($('#research').is(":checked")) { var f_research = true;}
else { var f_research = false; }
var url = '/api/VERSION/DATABALE/get?f_own='+ f_own +'&f_research='+ f_research
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
So need somehow combine this js. IF only selected options send this selectedServices if checked checkbox send only values from checkbox js. IF selected or clicked both send both values.
I try combine like this
$('.selectpicker').on('change'); or ('input[name="checkboxGroup1"]').on("click", function(){
selectedServices = $(this).val();
console.log("Filter clicked")
var own = false;
var research = false;
if($('#own').is(":checked")) { var f_own = true;}
else { var f_own = false; }
if($('#research').is(":checked")) { var f_research = true;}
else { var f_research = false; }
alert(selectedServices)
var url = '/api/VERSION/DATABALE/get?groupFilter='+ selectedServices + '&f_own='+ f_own +'&f_research='+ f_research
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
I dont getting any error, but it not change date in my datatable too, when i combine my js code
Any idea how to solve it? all help will be appreciated

Is there a way to catch an onchange trigger with a focusout by a button click?

The scenario is this modal window:
The inputs 2, 3 and 4 with an .on('change', function () {}); makes an AJAX call to a specified controller, that update the recod values and reload the value 1.
So the right, but not functional way is to:
click the input 1 and set the value
focusout it by clicking outside the input
AJAX reload value 1 updated
click input 2 and set the value
focus out it by clicking outside the input
AJAX reload value 1 updated
The user click confirm that call another controller that make some checks and change the status of an object (from Draft to Confirmed)
The problem
If I try this way:
click the input 1 and set the value
focusout it by clicking outside the input
AJAX reload value 1 updated
click input 2 and set the value
Click confirm button that call another controller and trigger the input change
Now, with this way the problem occurs because the confirm method doesn't receive yet the update from last onchange trigger and the check is not correct.
Is there a way to manage multiple AJAX from different triggers like onchange and onclick?
Something like if the below onclick is triggered:
// Trigger for button confirm inside timesheet sheet modal
$(document).on('click', 'button.js_confirm_timesheet_sheet', function (ev) {
var $button = $(this);
var wizard_id = $button.data()['wizardId'];
var sheet_id = $button.data()['sheetId'];
var values = {
'wizard_id': wizard_id,
'sheet_id': sheet_id,
};
confirm_sheet_distribution_hours(values);
});
Check if the click come from an input focus out, if yes trigger the onchange first and after the onclick
Maybe this solution can be a bad way to do this.
Little, triggers recap:
The inputs have an onchange trigger that writes data to backend object with an AJAX call that recompute values and return the new one
The confirm button check if everything is ok with an AJAX call and change the backend object status
The other workaround maybe can be to declare an object that keeps track of each changed input boxes and clear it on each AJAX success return.
Something like:
var changedData = {};
function update_wizard_data_and_modal(values, $input_elem, event) {
changedData[key] = $input_elem;
ajax.jsonRpc("/my/controller/path", "call", values)
.then(function (new_modal_values) {
$input_elem.removeClass('input-value-error');
if (!jQuery.isEmptyObject(new_modal_values)) {
if (new_modal_values.error_msg) {
var $content = $(new_modal_values.error_msg);
$content.modal({
backdrop: 'static',
keyboard: false
});
$content.appendTo('body').modal();
// Show error class
$input_elem.val('00:00');
$input_elem.addClass('input-value-error');
}
// Update the header values with hours to be distribuited
$('#header-wizard-values').html(new_modal_values.header_values);
// Update the hours to get payed available
$('.js_hours_to_get_payed').html(new_modal_values.hours_get_payed_values);
// Clear the changedData object
for (var member in changedData) delete changedData[member];
}
});
}
function confirm_sheet_distribution_hours(values) {
if jQuery.isEmptyObject(changedData){
ajax.jsonRpc("/confirm/controller/path", "call", values)
.then(function (response) {
if ('error' in response) {
//response in this case is the modal error template
$(response.error).appendTo('body').modal();
} else {
// Close modal and refresh the grid for current period
$('#modal_timesheet_sheet_confirm').modal('hide');
var sheet_item_data = {
'year': response.year,
'month': response.month,
};
update_grid_and_bars_values(sheet_item_data);
}
});
} else {
// TODO: trigger the change for element inside object and confirm
}
}
$(document).on("change", "input.distribution-input", function (ev) {
var $input = $(this);
var sheet_id = $('input[name="sheet_id"]').val();
var wiz_line_id = Number($input.attr('id').match(/\d+/)[0]);
var row_wizard_data = $input.closest('div.row').data();
var leave_type_id = row_wizard_data['leaveTypeId'];
var wizard_id = row_wizard_data['wizardId'];
var values = {
'sheet_id': Number(sheet_id),
'wizard_id': wizard_id,
'wiz_line_id': wiz_line_id,
'leave_type_id': leave_type_id,
'input_value': $input.val(),
};
var is_good_formatted = check_string_time_format($input, {});
if (is_good_formatted) {
update_wizard_data_and_modal(values, $input, ev);
}
});
// Trigger for button confirm inside timesheet sheet modal
$(document).on('click', 'button.js_confirm_timesheet_sheet', function (ev) {
ev.preventDefault();
ev.stopPropagation();
var $button = $(this);
var wizard_id = $button.data()['wizardId'];
var sheet_id = $button.data()['sheetId'];
var values = {
'wizard_id': wizard_id,
'sheet_id': sheet_id,
};
confirm_sheet_distribution_hours(values);
});
As suggested by Taplar I used a similar approach.
Here the javascript that manages the "onchange" of a wizard in the Odoo Frontend.
// Variable used for the last input changed when user click the Confirm button
var canConfirm = true;
/* Variable used for keep trace of the number of retry inside method
* confirm_sheet_distribution_hours
* */
var nr_of_try = 0;
function update_wizard_data_and_modal(values, $input_elem, event) {
if (event.type !== 'input') {
ajax.jsonRpc("/controller/path/...", "call", values)
.then(function (new_modal_values) {
canConfirm = true;
$input_elem.removeClass('input-value-error');
if (!jQuery.isEmptyObject(new_modal_values)) {
if (new_modal_values.error_msg) {
var $content = $(new_modal_values.error_msg);
$content.modal({
backdrop: 'static',
keyboard: false
});
$content.appendTo('body').modal();
// Show error class
$input_elem.val('00:00');
$input_elem.addClass('input-value-error');
}
// Update the header values with hours to be distribuited
$('#header-wizard-values').html(new_modal_values.header_values);
// Update the hours to get payed available
$('.js_hours_to_get_payed').html(new_modal_values.hours_get_payed_values);
}
});
} else {
canConfirm = false;
}
}
function set_the_amount_on_wizard($input, values, event) {
if (event.type !== 'input') {
ajax.jsonRpc("/controller/path/...", "call", values)
.then(function (response) {
canConfirm = true;
if ('error' in response) {
//response in this case is the modal error template
$(response.error).appendTo('body').modal();
// Reset input value (backend reset the TransientModel value)
$input.val('00:00')
}
});
} else {
canConfirm = false;
}
}
function confirm_sheet_distribution_hours(values) {
if (canConfirm) {
ajax.jsonRpc("/controller/patH/...", "call", values)
.then(function (response) {
if ('error' in response) {
//response in this case is the modal error template
$(response.error).appendTo('body').modal();
} else {
// Close modal and refresh the grid for current period
$('#modal_timesheet_sheet_confirm').modal('hide');
var sheet_item_data = {
'year': response.year,
'month': response.month,
};
update_grid_and_bars_values(sheet_item_data);
}
});
} else {
/*Try six times to confirm the sheet (Until the onchange doesn't write
* new values the AJAX call doesn't set canConfirm as True
* */
if (nr_of_try <= 5) {
setTimeout(function () {
nr_of_try++;
confirm_sheet_distribution_hours(values);
}, 500);
}
}
}
//Trigger that monitorate hours distribution change
$(document).on("input change", "input.distribution-input", function (ev) {
var $input = $(this);
var sheet_id = $('input[name="sheet_id"]').val();
var wiz_line_id = Number($input.attr('id').match(/\d+/)[0]);
var row_wizard_data = $input.closest('div.row').data();
var leave_type_id = row_wizard_data['leaveTypeId'];
var wizard_id = row_wizard_data['wizardId'];
var values = {
'sheet_id': Number(sheet_id),
'wizard_id': wizard_id,
'wiz_line_id': wiz_line_id,
'leave_type_id': leave_type_id,
'input_value': $input.val(),
};
var is_good_formatted = check_string_time_format($input);
if (is_good_formatted) {
update_wizard_data_and_modal(values, $input, ev);
}
});
//Trigger that monitorate hours distribution change
$(document).on("input change", "input.payment-hour-input", function (ev) {
var $input = $(this);
var row_wizard_data = $input.closest('div.row').data();
var wizard_id = row_wizard_data['wizardId'];
var values = {
'wizard_id': wizard_id,
'input_value': $input.val(),
};
var is_good_formatted = check_string_time_format($input);
if (is_good_formatted) {
set_the_amount_on_wizard($input, values, ev);
}
});
// Trigger for button confirm inside timesheet sheet modal
$(document).on('click', 'button.js_confirm_timesheet_sheet', function (ev) {
var $button = $(this);
var wizard_id = $button.data()['wizardId'];
var sheet_id = $button.data()['sheetId'];
var values = {
'wizard_id': wizard_id,
'sheet_id': sheet_id,
};
// Variable used for retry sheet confirmation until canConfirm is not True
// Max repeat call is 6 times
nr_of_try = 0;
confirm_sheet_distribution_hours(values);
});
In simple words.
When the user is typing on inputs boxes the type input inside on.() set the variable canConfirm to false.
This prevents case when user changes values and click to the Confirm buttons immediately after.
In fact if the user changes some input box and immediately click "Confirm" the AJAX call starts only if the flag is true, if not the method calls it's self six times every 500 ms.
Let me know if there is some better way to doing that.
Thanks
PS: I will try a better approach with a DTO backend that clone data from model and manage updates like onchange cache.
Inspired by: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Messenger.html

jQuery Trigger Click not work at first click

I have a trouble with jquery trigger click. I need to play audio from audio tag via trigger click. When i click first time on first element it work, but if I click in another element, the first click not work. If i click 2nd time it will be work.
var Audioplaying = false;
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (Audioplaying == false) {
Audioplaying = true;
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
The variable Audioplaying is shared, it is not unique so you probably want it to be unique per element. So use data() to keep track of the state for each player.
jQuery('.playAudio').click(function(e) {
var player = jQuery(this).next('.audioPlayer');
var playerID = player.attr('id');
var playerState = player.data('isPlaying') || false; // get if it is running
player.data('isPlaying', !playerState); // update the boolean
var playerBTN = jQuery(this);
if (!playerState) {
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
Maintain the state of each button separately. so, you can use an object with it's 'id' as the key.
example : { button_id : true/false }
var Audioplaying = {};
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (!Audioplaying[playerID]) {
Audioplaying[playerID] = true; // every button has it's own state maintained in the object.
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying[playerID] = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
Hope it helps you arrive at a optimal solution.

localStorage clears on refresh, parse & stringify not working

Working on a practice app with localStorage, but the stored data is getting cleared on page refresh. Based on answers to similar questions, I've used JSON.stringify(); on setItem, and JSON.parse(); on getItem, but still no luck. Am I using those methods in the wrong way? For reference, #petType and #petName are input IDs, and #name and #type are ul IDs. Thanks!
var animalArray = [];
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
localStorage.setItem("petType", JSON.stringify(type));
localStorage.setItem("petName", JSON.stringify(name));
animalArray.push(type,name);
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty array
animalArray.length = 0;
//empty input
$("input").val("");
var storedName = JSON.parse(localStorage.getItem("petName"));
var storedType = JSON.parse(localStorage.getItem("petType"));
//append localStorage values onto ul's
$("#name").append("<li>" + storedName + "</li>");
$("#type").append("<li>" + storedType + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
It appears to clear because you are not loading data from it when the page loads. There are multiple bugs in the code:
It appears that you're only saving the last added pet to localStorage, which would create inconsistent behaviour
Setting animalArray.length to 0 is incorrect
animalArray.push(type, name); is probably not what you want, since it adds 2 items to the array, do something like animalArray.push({type: type, name: name});
logPets can just use the in memory array, since it's identical to the one saved
Fixed code:
var storedArray = localStorage.getItem("animalArray");
var animalArray = [];
if(storedArray) {
animalArray = JSON.parse(storedArray);
}
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
animalArray.push({type: type, name: name});
localStorage.setItem("animalArray", JSON.stringify(animalArray));
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty input
$("input").val("");
//append localStorage values onto ul's
$("#name").append("<li>" + element.name + "</li>");
$("#type").append("<li>" + element.type + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
A quick fiddle to demo it: https://jsfiddle.net/rhnnvvL0/1/

Dynamic dropdowns filtering options with jquery

I am trying to filter one dropdown from the selection of another in a Rails 4 app with jquery. As of now, I have:
$(document).ready(function(){
$('#task_id').change(function (){
var subtasks = $('#subtask_id').html(); //works
var tasks = $(this).find(:selected).text(); //works
var options = $(subtasks).filter("optgroup[label ='#{task}']").html(); // returns undefined in console.log
if(options != '')
$('#subtask_id').html(options);
else
$('#subtask_id').empty();
});
});
The task list is a regular collection_select and the subtask list is a grouped_collection_select. Both which work as expected. The problem is that even with this code listed above I can't get the correct subtasks to display for the selected task.
NOTE: I also tried var tasks=$(this).find(:selected).val() that return the correct number but the options filtering still didn't work.
Try something like this instead (untested but should work).
$(function () {
var $parent = $('#task_id'),
$child = $('#subtask_id'),
$cloned = $child.clone().css('display', 'none');
function getParentOption() {
return $parent.find('option:selected');
}
function updateChildOptions($options) {
$child.empty();
$child.append($options);
}
$parent.change(function (e) {
var $option = getParentOption();
var label = $option.prop('value'); // could use $option.text() instead for your case
var $options = $cloned.find('optgroup[label="' + label + '"]');
updateChildOptions($options);
});
});

Categories