I have been testing with radio buttons. Everything seems okay until i ran it through JS lint. I fixed all errors except one:
Unexpected 'for'
for (i = 0; i < radios.length; i += 1) {
Here is my Javascript:
/*global body,window,document,alert*/
(function () {
"use strict";
var UIlogic;
UIlogic = {
myLoad: function () {
var elems, elemText, btn1, winter, summer, fall, spring, header, btns;
winter = "<div><input type='radio' name='cb' id='cbA' value='0'/><label for='cbA'>Winter</label></div>";
summer = "<div><input type='radio' name='cb' id='cbB' value='1'/><label for='cbB'>Summer</label></div>";
fall = "<div><input type='radio' name='cb' id='cbC' value='2'/><label for='cbC'>Fall</label></div>";
spring = "<div><input type='radio' name='cb' id='cbD' value='3'/><label for='cbD'>Spring</label></div>";
header = "Header";
btns = "<br /><button class='btns' id='btn1'>Go!</button>";
elemText = "Menu/nav";
elems = "<center><div>" + header + "</div></center>";//title
elems += "<div>" + elemText + "</div></center>";//menu
elems += "<div id='container'><br />";//container opens
elems += "<div id='div1'>" + winter + "</div>";
elems += "<div id='div2'>" + summer + "</div>";
elems += "<div id='div2'>" + fall + "</div>";
elems += "<div id='div2'>" + spring + "</div>";
elems += "<div id='div3'>" + btns + "</div>";
elems += "</div>";//container closes
elems += "<h6><div id='footer'>Ehawk 2015</div></h6>";
body.innerHTML = elems;
btn1 = document.getElementById("btn1");
btn1.addEventListener('click', UIlogic.intoFunction, false);
},
intoFunction: function () {
var radios, found, i = 0;
radios = document.getElementsByName("cb");
found = 1;
for (i = 0; i < radios.length; i += 1) {//issue occurs here
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if (found === 1) {
alert("Please Select Radio");
}
}
};
window.onload = function () {
UIlogic.myLoad();
};
}());
Am i running my loop wrong? why would JSlint see a problem here even thought the code works? I could really use some insight on loops, as i have the most issues with them. I have been told not to use them, but i don't see the problem with running a loop to detect radio buttons and checked radios. Is this something i should be concerned with?
JSLint suggests you use other loops such as forEach. http://www.jslint.com/help.html#for
You can just select the tolerate "for statement" option at the bottom if this bothers you but the code looks fine.