localStorage of Radio Button

2019-06-09 09:12发布

问题:

I cannot seem to find a simple localStorage implementation for radio buttons.

This example seems to actually use cookies rather than the localStorage.

This example doesn't have an answer.

I would like to try to avoid setting the val of an input because there will be hundreds of different lists. The html:

   <ol type="A" class="quizzy">
       <li><label><input type="radio" name="set1" class="mcObj" onclick="return correctIt(5)"><span>Lorem</span></label></li>
       <li><label><input type="radio" name="set1" class="mcObj" onclick="return correctIt(2)"><span>Lorem</span></label></li>
       <li><label><input type="radio" name="set1" class="mcObj" onclick="return correctIt(4)"><span>Lorem</span></label></li>
       <li><label><input type="radio" name="set1" class="mcObj" onclick="return correctIt(4)"><span>Lorem</span></label></li>
   </ol>

The problem is that it's always the last input that gets stored regardless of what button that the user checks.

The javascript:

    ...
    } else if($(this).is('input[type="radio"]') === true) {
        //If this is a radio input...
            if(content !== null) {
                $('input[name="'+getInputName+'"]').each(function(){
                //...check each button...
                    if($(this).val() === content) {
                    //...and if the value of "content" (referenced above) matches...
                        $(this).attr('checked','checked');
                        //...check this radio button.
                    }
                });
            }

            $(this).bind('click',function(){
                localStorage[getInputName] = $(this).val();
                //store the value of the button whenever one is clicked
                //alert('foo');
            });
    ...

A link to the codepen example.

Anyone know how to store the radio buttons? (And sorry if it's below-average code quality).