简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM