javascript - check at least one radio button is selected on the page

前提是你 提交于 2020-01-07 05:38:07

问题


i am trying to check that at least one of my radio buttons are checked on the page, they are in different groups so i have tried to create an aray of all the groups and run therough them but i cant seems to see what is wrong with the code anyone know what i am doing wrong ?

function atLeastOneRadio() { 
      var chx = document.getElementsByTagName('input');
      var day = new array();
      day[0] = "monday";
      day[1] = "tuesday";
      day[2] = "wednesday";
      day[3] = "thursday";
      day[4] = "friday";
      for (var i=0; i<chx.length; i++) {
        if (chx[i].type == 'radio' chx[i].name == day[i] && chx[i].checked) {
          return true;
        } 
      }
      return false;
    }

回答1:


If you have jQuery it might be a bit shorter.

Something like:

//returns number of elements checked
$("input:checked").size();


//if you need to check if the name of the element is equal to something
$("input:checked").each(function(i){
    return($.inArray(this.name, days));
});



回答2:


for (var i=0; i<chx.length; i++) {
   for (var x=0; x< day.length;x++) {
        if (chx[i].type == 'radio' chx[i].name == day[x] && chx[i].checked) {
          return true;
        } 
    }
}


来源:https://stackoverflow.com/questions/14667947/javascript-check-at-least-one-radio-button-is-selected-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!