开发者

why does the web form submit, even when no content is input?

开发者 https://www.devze.com 2023-02-10 20:51 出处:网络
<script language=\"JavaScript\"> function chkname (){ var ip = document.getElementsById(\"user\");
<script language="JavaScript"> 
    function chkname (){
        var ip = document.getElementsById("user");

        if(ip==""){
            alert("please input something!");
            return false;
        }
    }
</script>

<form name="" id="Editor"  method="post" action="wrightchk.php" >
    <input  id="user" type="text"  >
    <input type="submit"  onClick="chkname()">
</form&g开发者_开发知识库t;

When the user doesn't input content, the form submits and triggers a redirect. I want it so that when no content is input, the form alerts, and does not redirect.


The variable ip contains a reference to the input element, you need to use the value proeprty to get it's content, and the name of the method is getElementById, not getElementsById:

var ip = document.getElementById("user").value;

To prevent the form to be posted when the validation fails, you need to return the result from the function in the event:

<input type="submit" onClick="return chkname();">

You need a name attribute on the input field in order for it to be included in the form data when posted:

<input id="user" name="user" type="text">
0

精彩评论

暂无评论...
验证码 换一张
取 消