How can I check whether a radio button is selected with JavaScript?

前端 未结 28 2468
面向向阳花
面向向阳花 2020-11-22 00:58

I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?

28条回答
  •  悲&欢浪女
    2020-11-22 01:44

    this is a utility function I've created to solve this problem

        //define radio buttons, each with a common 'name' and distinct 'id'. 
        //       eg- 
        //           
        //param-sGroupName: 'name' of the group. eg- "storageGroup"
        //return: 'id' of the checked radioButton. eg- "localStorage"
        //return: can be 'undefined'- be sure to check for that
        function checkedRadioBtn(sGroupName)
        {   
            var group = document.getElementsByName(sGroupName);
    
            for ( var i = 0; i < group.length; i++) {
                if (group.item(i).checked) {
                    return group.item(i).id;
                } else if (group[0].type !== 'radio') {
                    //if you find any in the group not a radio button return null
                    return null;
                }
            }
        }
    

提交回复
热议问题