Simple JavaScript Checkbox Validation

前端 未结 11 1990
长情又很酷
长情又很酷 2020-12-10 03:56

I usually work with PHP so sadly don\'t have some basic JS principles down. This is all I want to accomplish--I\'ve seen many posts on this topic but they are usually beyon

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 04:17

    Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked. By using checked property we check whether the checkbox is selected or not. cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"

    You can do the following:

    function validate() {
      var cbox = document.forms["myForm"]["gender"];
      if (
        cbox[0].checked == false &&
        cbox[1].checked == false &&
        cbox[2].checked == false
      ) {
        alert("Please Select Gender");
        return false;
      } else {
        alert("Successfully Submited");
        return true;
      }
    }
    Male Female Other

    Demo: CodePen

提交回复
热议问题