runeveryday
runeveryday

Reputation: 2799

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

<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>

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.

Upvotes: 0

Views: 71

Answers (1)

Guffa
Guffa

Reputation: 700302

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">

Upvotes: 1

Related Questions