javascript验证无法正常工作

时间:2014-06-18 05:50:45

标签: javascript

我有输入字段和提交按钮..

        <form action="" method="post">
           <input type="text" name="sponsar_name" id="sponsar_name" />
          <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="validate()" >
    </form>

      function validate()
    {
        var flag = 0;
    if(document.getElementById("sponsar_name").value == null || document.getElementById("sponsar_name").value == "")
        {
            document.getElementById("sponsar_name").style.borderColor = 'red';
            flag = 1;
            }
            else
            {
                        document.getElementById("sponsar_name").style.borderColor = '';
                }

                if(flag==1)
                {
                    return false;
                }
                else
                {
                    return true;
                }

    }
                     </script>

我已经在提交按钮上应用了一个功能。这已申请验证..代码是..

当我点击提交按钮时,它会显示文本框的红色背景,但会立即刷新页面..如果文本框为空,则不应刷新页面..但在我的代码中它正在这样做...任何人都可以帮助我??

4 个答案:

答案 0 :(得分:1)

尝试

<form action="" method="post">
   <input type="text" name="sponsar_name" id="sponsar_name" />
   <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="return validate()" >
</form>

答案 1 :(得分:0)

您需要使用onClick="return validate()"onSubmit="return validate()"。它将解决问题。

使用onClick="return validate()"

<form action="" method="post">
    <input type="text" name="sponsar_name" id="sponsar_name" />
    <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="return validate()" >
</form>

使用onSubmit="return validate()"

<form action="" method="post" onSubmit="return validate()">
    <input type="text" name="sponsar_name" id="sponsar_name" />
    <input type="submit" value="Submit"  class="btn-submit" name="submit">
</form>

答案 2 :(得分:0)

你需要这样做,

<input type="submit" value="Submit" class="btn-submit" name="submit" onClick="return validate()" >

如果您在方法中返回false,则表单将不会提交。

答案 3 :(得分:0)

更改您的表单:删除onClik功能并在表单标题上添加onSubmit

<form action="" method="post" onsubmit="return validate()">
           <input type="text" name="sponsar_name" id="sponsar_name" />
          <input type="submit" value="Submit"  class="btn-submit" name="submit"/> 
    </form>
相关问题