Help - Search - Members - Calendar
Full Version: Multiple RadioButton state save and restore.
HTMLHelp Forums > Programming > Client-side Scripting
White Hat Man
Hello there! smile.gif

I already have a code of saving locally the state of a Radio Button. However, I find it difficult to save and restore the state of a second or third Radio Button.

The "save" and "restore" of the radio button is done in a script with the help of cookies.

Any ideas of how i can save and restore many radio button states? Is there a better way?


More specifically, the first form named "form1"-"box1" works fine. I have tried duplicating and adjusting the script code to work for the form named "form2"-"box2" with bad results. Later on, I will add more forms ("form3"-"box3", "form4"-"box4", "form5"-"box5" and so on).

Attaching a part of the code.

CODE
<html>
<head>

<p>Radio buttons</p>

<script type="text/javascript">

  function setCookie(isName,isValue){
    document.cookie = isName+"="+isValue;}

  function getCookie(isName){
    cookieStr = document.cookie;
    startSlice = cookieStr.indexOf(isName+"=");
    if (startSlice == -1){return false}
    endSlice = cookieStr.indexOf(";",startSlice+1)
    if (endSlice == -1){endSlice = cookieStr.length}
    isData = cookieStr.substring(startSlice,endSlice)
    isValue = isData.substring(isData.indexOf("=")+1,isData.length);
    return isValue;}

  function saveState(){
    for (i=0; i<7; i++)
      {if (document.forms.form1.box1[i].checked){boxIndex = i}}
    setCookie('radioState',boxIndex)}

  function restoreState(){
    isRadio = getCookie('radioState');
    if(isRadio){document.forms.form1.box1[isRadio].checked = true}}
  window.onload=restoreState;
  window.onbeforeunload=saveState;
</script>


<form name='form1'>
  Name of form1:
  <input type="radio" name="box1" value="20"> 20
  <input type="radio" name="box1" value="25"> 25
  <input type="radio" name="box1" value="30"> 30
  <input type="radio" name="box1" value="35"> 35
  <input type="radio" name="box1" value="40"> 40
  <input type="radio" name="box1" value="45"> 45
  <input type="radio" name="box1" value="50"> 50
</form>


<form name='form2'>
  Name of form2:
  <input type="radio" name="box2" value="20"> 20
  <input type="radio" name="box2" value="25"> 25
  <input type="radio" name="box2" value="30"> 30
  <input type="radio" name="box2" value="35"> 35
  <input type="radio" name="box2" value="40"> 40
  <input type="radio" name="box2" value="45"> 45
  <input type="radio" name="box2" value="50"> 50
</form>


</body>
Christian J
In principle you might loop through the forms, then use a nested loop to get each form's radio button value. In this process, all the forms' radion button values might be added to a string variable. Finally that string is stored in the cookie.
White Hat Man
Thank you for the answer. The problem is that there are about 20 more radiobuttons and in practice going through a loop seems very frustrating. I also considered the localStorage of html5 but i get many errors when getting the array...........................
If nothing works I can assign one cookie for each radio value but I really want to avoid that.


CODE
    //this function runs everytime there is a click from the mouse to update         and save the radio values (logicaly)
    function saveState() {
          //gets every object from the main form to read and save it.
              localStorage.setItem("flag", "set");
            var data = $("#mainform").serializeArray();
            $.each(data, function(i, obj) {
              localStorage.setItem(obj.name, obj.value);
            });
            console.log(data); //console shows only one object which is the first one (pid) with one value
        }

    //this function must be run each time the window loads to initialize the radio values (logicaly)
      function onloadfunction() {
        if (localStorage.getItem("flag") == "set") {
          //gets every object from the main form to read and restore it.
          var data = $("#mainform").serializeArray();
          $.each(data, function(i, obj) {
            $("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
          });
        }
      }
      window.onload=onloadfunction;
      window.onbeforeunload=saveState;
    //end of ideas...............
    </script>

    <body>
    <form id="mainform" name='mainform'>
Christian J
QUOTE(White Hat Man @ Feb 13 2016, 03:08 PM) *

The problem is that there are about 20 more radiobuttons and in practice going through a loop seems very frustrating.

I'd say the opposite is the case: the more radio buttons you have, the more useful a loop becomes.

QUOTE
I also considered the localStorage of html5 but i get many errors when getting the array...........................

AFAIK, both cookies and localStorage only save strings, not array objects. So you may have to create a string like

CODE
box1=20, box2=30, box3=20

...etc, before saving to the cookie.
White Hat Man
I thought you meant to do one loop for each box. How can i make a loop to process a different cookie each time for a different radio value? Or every value in one cookie? I am really out of ideas about the scripting part.

You are right about that but for the localStorage, I meant that i cant get the array to be turned and saved into a string.

To be honest I would prefer the localStorage method because even if it is harder for me to code, it works in Chrome. For some reason Chrome does not recognize local cookies processed this way. Firefox and Opera do (with the exact same code of cource).
Christian J
Here's a sample. It doesn't create a cookie, just creates a string of the radio button values:

CODE
<script type="text/javascript">
function get_radio_values()
{
    var form=document.getElementsByTagName('form');
    var radio_values='';
    for(var i=1; i<form.length+1; i++)
    {
        var input=form[i-1].getElementsByTagName('input');
        for(var j=0; j<input.length; j++)
        {
            if(input[j].type=='radio' && input[j].name=='box'+i && input[j].checked)
            {
                radio_values+='box'+i+'='+input[j].value+',';
            }
        }
    }
    document.getElementById('result').innerHTML=radio_values;
}
</script>

<form>
<input type="radio" name="box1" value="10" checked>10<br>
<input type="radio" name="box1" value="20">20
</form>

<form>
<input type="radio" name="box2" value="15" checked>15<br>
<input type="radio" name="box2" value="25">25
</form>

<form>
<input type="radio" name="box3" value="30" checked>30<br>
<input type="radio" name="box3" value="35">35
</form>

<input type="button" value="Get radio values" onclick="get_radio_values();">

<p id="result"></p>
Christian J
QUOTE(White Hat Man @ Feb 14 2016, 02:10 AM) *

For some reason Chrome does not recognize local cookies processed this way. Firefox and Opera do (with the exact same code of cource).

Maybe cookies are disabled in your copy of Chrome? I also recall Chrome doesn't allow some things on pages opened from your computer's local file system (test on your web server instead).

Your visitors also need to be informed that the page sets a cookie, so they can make sure cookies are enabled. You may also want to inform users that javascript is needed for this to work (a message in a NOSCRIPT element might be enough).
White Hat Man
I did some research and even if chrome has cookies enabled it does not allow access to some things as you said.

Oh well..... Ill need to figure a way with localStorage............. :/
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2018 Invision Power Services, Inc.