【问题标题】:Validation of percentage in javascript [closed]在javascript中验证百分比[关闭]
【发布时间】:2015-05-24 14:30:50
【问题描述】:

我似乎无法验证百分比。 需要你们帮我解决!

 function validate()
    {
       s
   if( document.myForm.outputPercentage.value <= 0||>=100

   {
     alert( "Please the correct percentage." );
     document.myForm.outputPercentage.focus() ;
     return false;



<form name="myForm"  onsubmit="return(validate());">

Last output percentage: <input type"text" name="outputPercentage" id="outputPercentage" />&<br/><br/>


<input type="submit" value="Submit" />

【问题讨论】:

  • s 只是一个错字吗?
  • 您的代码中有几个语法错误。
  • 另外,你必须检查每个条件,像这样if (something &lt;= 0 || something &gt;= 100)
  • 另外,表单元素 value 是字符串,而不是数字。

标签: javascript html validation


【解决方案1】:

我已经更正了您的代码,使其可以正常工作:

<html>
<head>
    <script type="text/javascript">
        function validate() {
            var outputPercentageString = document.myForm.outputPercentage.value;
            var outputPercentage = parseInt(outputPercentageString);
            if (outputPercentage <= 0 || outputPercentage >= 100) {
                alert("Please the correct percentage.");
                document.myForm.outputPercentage.focus();
                return false;
            }
        }
    </script>
</head>
<body>

    <form name="myForm"  onsubmit="return(validate());">

        Last output percentage: <input type="text" name="outputPercentage" id="outputPercentage" />%
        <br/><br/>


        <input type="submit" value="Submit" />
    </form>
</body>

</html>
  1. 自行删除所有“s”。
  2. 网页上的所有内容都是字符串,因此要将百分比与数字进行比较,您必须使用 parseInt 将其转换为数字。
  3. type"text" 应该是 type="text"
  4. 如果你打开一个括号{,那么你必须在之后关闭它}
  5. 将javascript放入页面&lt;head&gt;元素的&lt;script&gt;标签中
  6. 我已将所有内容放入 &lt;html&gt; 元素中。
  7. 了解 getElementById() 的作用。每个人都使用 id 来获取对网页元素的引用,而不是名称。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多