How to change a single value of checkbox inside a localStorage? - javascript

I'm trying to change a value inside localstorage. This item is the status of a checkbox. I want, everytime that a checkbox is checked to set the value to true or false of that checkbox. I tried many ways until I realized that there is no way you can change a value without using JSON.
To add the value I use:
localStorage.setItem("status-" + i, $status.is(":checked"));
and to delete I use:
var parentId = $this.parent().attr('id');
localStorage.removeItem("'" + parentId + "'");
Now to change the value I tried:
$itemList.delegate("#status-" + i, 'click', function(e) {
var $this = $(this);
var parentId = this.parent().attr('id');
if ($this.is(":checked")) {
localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// Note that alert here works.
}
});
This is how my local storage looks like:
I hope someone could help me. I've been working on it for few days...
Here is a fiddle for it: http://jsfiddle.net/CC5Vw/7/
Thanks alot

look at this: http://jsfiddle.net/Rh4Au/6/ works well..
changes http://jsfiddle.net/CC5Vw/7/ to http://jsfiddle.net/Rh4Au/6/
line 30:
+ "<div class='checkbox'><input type='checkbox' class='test' id='status-" + i + "'></div>"
i chaged to j because i is the length and j is the iterator.
insertion after line 34:
var tempasd = orderList[j].split("-")[1];
if(localStorage.getItem("status-"+tempasd) == "true") {
$("#status-"+j).get(0).checked = true
}
else {
$("#status-"+j).get(0).checked = false
}
}
The code loads the data from localStorage and check in the checked checkboxes.
The tempasd is a temporary variable store the current ID num of the checkbox (because they not always come ascending.
changes from line 99 to 117:
// ON STATUS CLICK
console.log('i=',i,' j=',j, 'k=',k);
$itemList.delegate("#status-" + i, 'click', function(e) { // ON CLICK
var $this = $(this);
var parentId = $this.attr('id');
if ($this.is(":checked")) {
console.log('set ', parentId, 'to foo');
localStorage.setItem(parentId, 'foo');
// localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// localStorage.setItem($this.parent().attr('checked', true));
// window.location = "http://mail.aol.com"
}
});
to
// ON STATUS CLICK
console.log('i=',i,' j=',j, 'k=',k);
var tempxx;
for(tempxx = 0;tempxx < j; tempxx++) {
$itemList.delegate("#status-" + tempxx, 'click', function(e) { // ON CLICK
var $this = $(this);
var parentId = $this.parent().parent().attr('id').split("-")[1];
console.log('set ', parentId, 'to foo');
localStorage.setItem("status-"+parentId, $this.is(":checked"));
// localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// localStorage.setItem($this.parent().attr('checked', true));
// window.location = "http://mail.aol.com"
});
}
i need the loop because it needs to delegate an event to each checkbox, and also the event must set the localStorage to false when it gets unchecked.
btw the .parent().parent() is unnecesarry now because i fixed at line 30.

Related

Check if the previous value is changed and if changed put the previous value before changed in a log table and print that log table on screen

I am trying to work on a worksheet in which user can change the value, but i want that when user change the value the previous value should store somewhere and then can be printed on a change log table on screen
I have tried the following code
$("classPreviousValue").on('focusin', function() {
$(this).data('val', $(this).val());
});
$("classPreviousValue").on('change', function() {
var $prev = $(this).data('val');
var $current = $(this).val();
if ($prev !== $current) {
alert ("Things changed");
$(this).css("color", $currentDayColor);
$("#divChangeLog").html($("#divChangeLog").html() + "<br>Value changed from $prev");
};
});
Classes start with a period .classPreviousValue not classPreviousValue. And try switching on('focusin' to each to loop through all of them without the need for user interaction. Also at the end of the if statement, change data-val to the new value.
$(".classPreviousValue").each(function() {
$(this).data('val', $(this).val());
});
$(".classPreviousValue").on('change', function() {
var $prev = $(this).data('val');
var $current = $(this).val();
if ($prev !== $current) {
alert ("Things changed");
$(this).css("color", $currentDayColor);
$("#divChangeLog").html($("#divChangeLog").html() + "<br>Value changed from " + $prev);
$(this).data('val',$current); //set data-val to new value
};
});

Strange behavior with on/off click and jQuery?

so I'm trying to use link clicks to add buttons to a div, then be able to click those buttons to remove them and re-enable the original links to be clicked again so you can add and remove an infinite number of times. I have it mostly working, but after trying to re-enable the click function I'm getting strange behavior.
1) You need to click the link twice to re-append the button and
2) Sometimes I'm getting multiple instances of the appended button in the div now.
Here is my code:
var selections = ' ';
function add_Button() {
jQuery(".form-unselected").click(function (e) {
jQuery(this).removeClass('form-unselected').addClass('selected').off('click');
var title = jQuery(this).attr("title");
var id = jQuery(this).attr("href");
selections += title + ', ';
var button_content = jQuery('<button class="content-button">').html(title).attr("title", title).attr("id",id);
event.preventDefault();
$( "#selected-items" ).append(button_content);
console.log(selections);
});
}
add_Button();
jQuery(document).on('click','.content-button', function(e){
var removed_content = jQuery(this).attr("title") + ', ';
selections = selections.replace(removed_content,'');
var href = jQuery(this).attr("id");
jQuery(".add-to-form[href='"+ href +"']").addClass('form-unselected').removeClass('selected').on('click', add_Button );
jQuery(this).remove();
console.log(selections);
});
The selections variable is a comma separated list of the values for another purpose, but I'm getting the duplicates there as well. Thanks in advance!
You should not dynamically add and remove the click handler. Initially add the click handlers to all the buttons. Then when clicked you can query the status and decide.
Also there was an unknown reference event that did not match the argument e.
And, repeating jQuery(this) is expensive. Store this value in a local variable and refer to it instead. The code below demonstrates all the changes.
var selections = ' ';
jQuery(".form-unselected").click(function (e) {
var $this = jQuery(this);
if ($this.hasClass("selected")) {
return;
}
$this.removeClass('form-unselected').addClass('selected');
var title = $this.attr("title");
var id = $this.attr("href");
selections += title + ', ';
var button_content = jQuery('<button class="content-button">').html(title).attr("title", title).attr("id",id);
e.preventDefault();
$("#selected-items").append(button_content);
console.log(selections);
});
jQuery(document).on('click','.content-button', function(e) {
var $this = jQuery(this);
var removed_content = $this.attr("title") + ', ';
selections = selections.replace(removed_content,'');
var href = $this.attr("id");
jQuery(".add-to-form[href='"+ href +"']").addClass('form-unselected').removeClass('selected');
$this.remove();
console.log(selections);
});

Storing check box in local storage

I'm able to store text how I want but cant get check boxes to work properly. It is storing the check box values as 'on' regardless if checked or not. How can I set is to store "off" by default and "on" when checked?
something that would achieve this:
var value = $(this).val() && $(this).prop(checked);
JS Fiddle: http://jsfiddle.net/cRJ23/17/
Storage.prototype.setObj = function (key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function (key) {
return JSON.parse(this.getItem(key))
}
var Survey = {},
Surveys = {},
save = function () {
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
if (localStorage.getObj('Surveys') != null) {
Surveys = localStorage.getObj('Surveys');
}
Surveys[$('#FirstName').val() + '.' + $('#LastName').val()] = Survey; //store in big list
localStorage.setObj('Surveys', Surveys);
}
Hope this helps:
var value = $(this).val();
var name = $(this).attr('name');
if($(this).hasClass('checkers')){
value = $(this).is(":checked")
if(value){
value='on';
}else{
value='off';
}
}
http://jsfiddle.net/juvian/cRJ23/22/
You should not use .val to check whether checkbox is selected, use .is('checked')
Instead of using .val()to get the state of a checkbox you should use .prop() or the property .checked
$('input, select, textarea').each(function () {
var value = ($(this).is('[type="checkbox"]')) ? this.checked :$(this).val(),
name = $(this).attr('name');
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
Working example: http://jsfiddle.net/cRJ23/24/
Working Fiddle http://jsfiddle.net/jFeLv/
The val function does not work like you would expect with check boxes, the way to get true or false from them is to use the is(':checked') function.
$(this).is(':checked')
The fiddle is a modified version of your code by modifying one line that seems to be working fine by shorthanding an if else for the variable "value" checking to see if it is a checkbox.
($(this).attr('type','checkbox') ? value = $(this).val() : value = $(this).is(':checked'));
I hope this helps.

Set value of a checkbox to "checked" when appending to another part of page

when a checkbox on my page is clicked, I grab it's containing elements and append the whole block to another part of the page. Like this:
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
I want the new checkbox to be checked when it is pasted into the favelist. Is there anything I can do to parentContent- which contains the HTML block of the checkbox & surrounding elements- so that it is already checked when it is appended?
You don't need to append a string to favelist, you can append a jQuery element right away. By doing this, all properties and styling set through the DOM will be kept, such as checked.
That means you can drop both $("<div />").append( and ).html().
The resulting code would be the following.
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("#food-" + id).clone(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
It will be faster as well.
Try this,
checked = this.checked,
Or
checked = $(check).prop("checked"),
in place of
checked = $(check).attr("checked"),
And Codition like,
if (checked === true) {
$(favelist).append(parentContent);
}
Full code,
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = this.checked,
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === true) {
$(favelist).append(parentContent);
}
});
I'll give this the old college try ...
$('.favourite').on('click','[type="checkbox"]',function(){
var chk = this.checked,
id = this.id.split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
$favelist = $(this).find(".content");
if (chk === "checked") {
$favelist.append(parentContent).find('input[type="checkbox"]').prop('checked');
}
});
This adds a little delegation action, as well as uses the vanilla JS versions of checked and id for performance purposes. It also eliminates the double-wrapping you were doing with favelist.

.wrap(); breaking prevent.Default();

I've written a custom form validation script, but for some reason, wrapping input[type=text] elements in <div class="inputWrapper" /> stops me from preventing input[type=submit]'s default setting.
Here's the relevant code:
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
Is breaking:
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
Why is this happening? If you need a more full script, let me know, and I'll just post the whole thing.
Alright, so for some reason, disabling that line of code allows .preventDefault on the input[type=submit] to work, but if I just use
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
It works fine. So here's the full script, what could cause this weirdness?
$(document).ready(function() {
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
$("textarea").wrap("<div class=\"inputWrapper\" />");
// validate text inputs on un-focus
$("input[type=text].required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate textareas on un-focus
$("textarea.required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
// check fields
$(this).parent("form").children("input.required").each(function() {
// check textboxes
if ($(this + "[type=text]")) {
if (!$(this).val()) {
$(this).addClass("error");
};
};
// end textboxes
// check textareas
$(this).parent("form").children("textarea.required").each(function() {
if (!$(this).val()) {
$(this).addClass("error");
};
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
if (!$("input[name=" + inputName + "]").is(":checked")) {
var inputId = $(this).attr("id");
$("label[for=" + inputId + "]").addClass("error");
};
};
// end checkboxes and radio buttons
});
// end fields
// submit form
var errorCheck = $(this).parent("form").children(".error").length > 0;
if (errorCheck == 0) {
$(this).parent("form").submit();
} else {
alert("You didn't fill out one or more fields. Please review the form.");
window.location = "#top";
};
// end submit form
});
// clear errors
$("input.required").each(function() {
// clear textboxes
if ($(this + "[type=text]")) {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
};
// end textboxes
// clear textareas
$("textarea.required").each(function() {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
var labelFor = $(this).attr("id");
$(this).click(function() {
$("input[name=" + inputName + "]").each(function() {
var labelFor = $(this).attr("id");
$("label[for=" + labelFor + "]").removeClass("error");
});
});
};
// end checkboxes and radio buttons
});
// end clear textbox errors
});
Alright, I was wrong about what the problem was. It's related to the line I thought it was, but it's actually having an issue finding the .error after I wrap the inputs.
Here's where the problem lies:
var errorCheck = $(this).parent("form").children(".error").length > 0;`\
var errorCheck = $(this).parent("form").children(".error").length > 0;
When you .wrap the text inputs, they are no longer children of the form. Use .find
By the way, $(this + "selector") is not valid. You probably want to use $(this).is("selector")
You will need some sort of reference maintained with the new DOM element. This would be placing it as an initialised DOM element in a variable first (not as a string as you did) and the same for the original element, which will be placed back in to maintain the event:
var $inputWrapper = $("<div class=\"inputWrapper\" />"),
$inputText = $("input[type=text]");
$inputText.wrap("<div class=\"inputWrapper\" />");
Then you can replace the element back in.

Categories