简体   繁体   English

提交前检查表单-JavaScript

[英]checking a form before submitting - JavaScript

I have the following form: 我有以下表格:

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Choose</title>
  <script type="javascript/text">

    function ischecked(){
        var check = document.getElementsByTagName( 'input' );
        for( var i = 0; i < check.length; i++ ){
        if( check[ i ].type == 'radio' && check[ i ].checked ){
            return true;
          }
        }
        return false;
    }

  </script>
</head>

<body>
  <form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">
    <h1>Choose</h1>

    <p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
    <br>
    <input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
    <br>
    <input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
    <br>
    <input type="submit" name="Submit" value="Go"></p>
  </form>


</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>

I wanted to make sure one of the radio buttons have been checked before submitting the form. 我想确保在提交表单之前已选中单选按钮之一。 However, it does not work, and the form is submitted anyways. 但是,它不起作用,并且无论如何都提交了表单。 What am I doing wrong here? 我在这里做错了什么?

您需要从内联事件处理程序return函数的结果。

You have to check against the value returned in your validation function directly in the attribute value. 您必须直接在属性值中检查验证函数中返回的值。 That is, in your HTML form declaration 也就是说,在您的HTML表单声明中

<form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">

you should write: 您应该写:

onsubmit="return ischecked();"

instead of: 代替:

onsubmit="ischecked();"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM