JavaScript beginner - another blocking point

A very useful advice you can give me is what set of tools you recommend me to use (for JavaScript programming).

Currently I am at a decent basic level of JavaScript knowledge. Still I cannot avoid several syntax mistakes from time to time. And I am doing debugging by toggle commenting over code lines. I have Sublime Text as text editor and nothing else. I suppose a linter and a debugging tool will be a must. Or also a more useful text editor? But I cannot decide what to choose. Seems all have pluses and minuses…

I appreciate, as usual, if you share your experience about these support tools.

The easiest way to locate syntax errors is to feed your code through http://jslint.com

I try a different approach for storing radio button selection with cookies.

<!DOCTYPE html>
<html>
<head>
<script>

</script>
</head>
<body onload = "checkCookie()">
<form name="myform" id="myform">
<p><input type="radio" name="myradio" id="myradio1" onchange = "checkForm(); setCookie('formString',frmString,1)">
<input type="radio" name="myradio" id="myradio2" onchange = "checkForm(); setCookie('formString',frmString,1)"></p>
</form>
<script>

function checkForm()
{
	var frm = new Array()
	frm[0] = document.getElementById("myradio1").checked
	frm[1] = document.getElementById("myradio2").checked
	frmString = frm.join()
	alert(frmString)
}

function setCookie(cname,cvalue,exdays)
{
	var d = new Date();
	d.setTime(d.getTime()+(exdays*24*60*60*1000));
	var expires = "expires="+d.toGMTString();
	document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = ca[i].trim();
		if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
}

function checkCookie()
{
	var frmString1 = getCookie("formString");
	var frm1 = frmString1.split(",")
	alert(frm1[0])
	alert(frm1[1])
	document.getElementById("myradio1").checked = frm1[0]
	document.getElementById("myradio2").checked = frm1[1]
}

</script>
</body>
</html>

I used some alerts to check if everything is fine and it is. Until the last step when I try to pass the value of frm1[i] to radio buttons.Seems they don’t care about frm1[i] value :slight_smile: Any would be frm1[i] value, the second radio button stays checked permanently when page reloads.

Obviously I am doing a mistake, but after hours of checking I was not able to realize what is wrong.

Probably how I try to pass the frm1[i] value to buttons is faulty, but I don’t realize why…

Please help me to understand this issue.

Thank you.

I couldn’t see where in your code you are doing this.

Also, as I said before in post#20 I would lose the inline event handlers.

I speak about:

document.getElementById("myradio1").checked = frm1[0]
	document.getElementById("myradio2").checked = frm1[1]

This doesn’t work. And II have to understand why. With your help :slight_smile:

Well, let’s look what frm1 contains.

Add the following to your script:

console.log(frm1);

// as before
document.getElementById("myradio1").checked = frm1[0]
document.getElementById("myradio2").checked = frm1[1]

Run the script, look at the console output and post it back here.

With “myradio1” checked returns the correct state of the buttons:

["true", "false"] 

Still, on the reloaded page the buttons appear: “myradio1” - unchecked, “myradio2” - checked.

If I try to display more radio buttons, at page reload always the last one will be checked, regardless what we checked before reload.

And the elements of frm1 array are always correct, respective to what button was checked.

Can this error be because [“true”, “false”] are strings? Maybe I should convert them? But to what?

I like the way you ignored my question there. Nicely done :slight_smile:
Anyway, I would do what you are asking like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Save buttonstate with cookies</title>
  </head>

  <body>
    <form id="myform">
      <p>
        <label>A: <input type="radio" name="radio" class="myRadio" id="a"></label>
        <label>B: <input type="radio" name="radio" class="myRadio" id="b"></label>
      </p>
    </form>

    <script>
      // Start cookie functions from Quirksmode
      // http://www.quirksmode.org/js/cookies.html
      //
      function createCookie(name,value,days) {
        if (days) {
          var date = new Date();
          date.setTime(date.getTime()+(days*24*60*60*1000));
          var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
      }

      function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
      }

      function eraseCookie(name) {
        createCookie(name,"",-1);
      } 
      // End cookie functions from Quirksmode

      function repopulateRadioButtons(){
        var selectedButton = document.getElementById(readCookie("buttonState"));
        selectedButton.checked = true;
      }

      var radios = document.getElementsByClassName("myRadio"),
          i;

      for(i=0; i<radios.length; i++){
        radios[i].addEventListener("change", function(){
          createCookie("buttonState", this.id, 7);
        }, false);
      }

      repopulateRadioButtons();
    </script>
  </body>
</html>

Please notice how I have removed the inline event handlers.

Any questions, just let me know.

DEMO

Thank you for the solution including a practical example of using EventListeners.

If I want to use this solution for checkboxes (instead radio buttons) what do I have to change?

About ignoring “the question”: I had no intention to do this. About what question do you speak?

You asked me to provide the console.log output and I did this. I did not notice any other question, sorry for this.

And I still want to understand which was the mistake in my method (except using EventHandlers, which I understood). Why with all correct elements the buttons do not select correctly?

Hi,

No probs :slight_smile:

I actually wrote a blog post on how to do this recently.
The blog post uses jQuery, but it should be easy enough to convert to plain JS.
Have a look at that and let me know if you have any questions.

Oops. I completely misread your response. Sorry, that was my mistake. :blush:
I struck through my comment in my post above to reflect the fact.

Were you attempting this locally or on a server?
The reason I ask is that some browsers (such as Chrome) don’t allow you to access cookies locally.

On a server. Exactly for the reason you mention, because I use Chrome.

The problem was with these lines:

document.getElementById("myradio1").checked = frm1[0];
document.getElementById("myradio2").checked = frm1[1];

What you wanted to be doing was this (boolean values):

document.getElementById("myradio1").checked = true;
document.getElementById("myradio2").checked = false;

But as you were getting the values by splitting a string which you retrieved from a cookie, this is what was happening:

document.getElementById("myradio1").checked = "true";
document.getElementById("myradio2").checked = "false";

Both of these evaluated to true, so the first button was always getting checked (as only one can be checked at once).

What you need to do is convert the strings to actual booleans.You can do that, like this:

function checkCookie()
{
  var frmString1 = getCookie("formString"),
      frm1 = frmString1.split(","),
      radio1State = (frm1[0] === "true"),
      radio2State = (frm1[1] === "true");
  document.getElementById("myradio1").checked = radio1State;
  document.getElementById("myradio2").checked = radio2State;
}

And it will work.

HTH

Thank you for your answer. It’s good that it came a little delayed because in the meanwhile I also discovered this issue and corrected it already.

But this doesn’t diminish your very helpful intentions.

Thank you for support.

That’s good - a great way to learn :slight_smile:
Out of interest, how did you solve this?