Storing check box in local storage - javascript

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.

Related

selectpicker : Get the data attribute of selected option

I'm having hard time in to getting the data attribute set to select option on bootstrap selectpicker .
I tried:
$('.selectpicker').on('changed.bs.select', function (e) {
var selected = e.target.value;
console.log("value : ", selected ); // gives selected value
console.log("data attribute: ", $(e.target).data("price"));
});
data attribute always returns undefined
what wrong I'm doing here ?
This works.
$('.selectpicker').on("changed.bs.select", function() {
var dataTypeAttribute = $('option:selected', this).attr("data-type");
});
Just specify id to select
$("#selectidhere").on("change", function () {
var dataname = $("option[value=" + $(this).val() + "]", this).attr('data-name');
alert(dataname);
});
Fiddle Link
$('.selectpicker').on('changed.bs.select', function (e) {
var selected = e.target.value;
console.log("value : "+selected ); // gives selected value
console.log("data attribute: "+$(e.target).attr("data-price"));});
$(".selectpicker").on("changed.bs.select",
function(e, clickedIndex, isSelected, oldValue) {
var arrayOfSelected = $('.selectpicker').eq(0).val();
console.log(arrayOfSelected);
});
It looks weird but it works perfectly so I don't care.

Change the value of select options based on the id attribute of the parent select element

I have multiple select options. If I select a specific select element, for example id="a" I want set the option values to 0.
$('#form option:selected').each(function() {
var id = $(this).attr('id');
if(id == 'a') {
val = 0;
} else {
val = 10;
}
console.log(val);
});
I got undefined value.
Part of the reason your jQuery wasn't working was because val is an undefined variable. You should have been using this.value in order to set/get the value of the option element.
Based on your comments, if the id is on the select element, it appears as though you want:
Example Here
$('form option:selected').each(function() {
var id = $(this).parent().prop('id');
this.value = id === 'a' ? 0 : 10;
});
It's worth mentioning that you can simplify your code by just using the .val() method. It will iterate over the elements, all you need to do is return a value:
Updated Example
$('form option:selected').val(function () {
return $(this).parent().prop('id') === 'a' ? 0 : 10;
});

jquery replace previous .after when the value changed

$("#paragraphDuration").bind('keyup', function() {
var fullDuration = $("#fullDuration").val(),
paragraphDuration = $(this).val();
$(this).after(function() {
if ($(this).val() != '') {
$(this).after(fullDuration - paragraphDuration + " min");
} else {
$(this).after("");
}
});
});
after i changed ("#paragraphDuration") many times , this is what i got:
this is not what i want !
how to replce previous .after when changing ("#paragraphDuration") value with new one ?
thank you
You need to overwrite the old value. It's best to not use .after to set the text, just use the .text() method on a predefined span element or so.
So for instance:
html
<input type="text" id="paragraphDuration"><span class="textContainer"></span>
js
$("#paragraphDuration").bind('keyup', function() {
var fullDuration = $("#fullDuration").val(),
paragraphDuration = $(this).val();
$(this).next('.textContainer').text(
$(this).val() !== ''
? (fullDuration - paragraphDuration + " min")
: ""
);
});

Changing value separation from "," to "-" (JS/Jquery)

I received some Jquery code for an HTML checkbox. Essentially, when checked, the value of the checkbox is placed in an input box. When I uncheck the box, the value is cleared from the input. However, when you check multiple checkboxes, a "," separates the values. Is there a way to seperate the values by "-" instead of ","? I tried playing around with the code and it just breaks the code. I am fairly new to JS/Jquery so if it is a simple answer, I apologize. I can provide more information if needed. A working JSFiddle with "," is here: https://jsfiddle.net/m240Laka/25/
My code is located here:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});
In the functions join() and split(), you need to pass in the delimiter you want, '-'. I suggest creating a local variable that you use, so it is easier to change this if needed.
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
Here is it in a jsfiddle.
In $.join() add the separator string parameter:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
UPDATE:
add the same in $.split()
choiceSelectionsArray = $choiceDisplay.val().split("-")....

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

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.

Categories