sandrina-p
sandrina-p

Reputation: 4160

LocalStorage input=radio || checkbox || select && show div if :checked on load

I have several questions about localStorage forms.

So I have these 3 types of inputs:

For each one I have a "special option" that shows a different input if that option is selected.

Plus, I have localStorage, but I can't make it work for checkbox and radio. It only works in textarea and input=select.

I have some scripts in jQuery:

What is missing - here i need your help

Fiddle: http://jsfiddle.net/sandrin4p/ury7dvt5/17/

Upvotes: 0

Views: 540

Answers (1)

Gijs Beijer
Gijs Beijer

Reputation: 624

Just setting the values for the select, radio and checkbox inputs won't do the trick. The .val() function just sets the value="" attribute.

if (localStorage.getItem("flag") == "set") {

        var data= $("#form54").serializeArray();

        $.each(data, function(i, obj) {

            console.log(i, obj);

            if($("[name='" + obj.name +"']").attr('type') === 'radio' ||
               $("[name='" + obj.name +"']").attr('type') === 'checkbox') {

              if(obj.name) $("[name='" + obj.name +"']").prop('checked', true);
              else $("[name='" + obj.name +"']").prop('checked', false);

            } else if( $("[name='" + obj.name +"']").attr('type') === 'select') {
                if(obj.name) $("[name='" + obj.name +"'] option[value='" + obj.value +"']").prop('selected', true)
                else $("[name='" + obj.name +"'] option[value='" + obj.value +"']").prop('selected', false)

            } else 
              $("[name='" + obj.name +"']").val(localStorage.getItem(obj.name) );
            }

        });

    }

should do the trick. (sorry for any typos just did this quickly (and i dont know if your object has a .value prop.

But i think you get the idea.

Good luck

Upvotes: 1

Related Questions