0
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <form>
        Name:<input type="text" id="t1"> <br> Gender: <input
            type="radio" name="sex" value="male">male <input type="radio"
            name="sex" value="female">female <br> <input
            type="submit" value="submit" onClick="myFunction()">
    </form>


    <script type="text/javascript">
        function myFunction() {
            var str = document.getElementById("t1").value;
            if (str == "") {
                alert("plz enter anything");
            }
        }
    </script>


</body>
</html>

I want to validate when there is no input from user and if user is pressing submit button then it should alert "enter any thing" but it is not working.......why I don't know

2
  • 1
    Its working fine .....you plz check once again Commented Oct 1, 2013 at 12:29
  • @DineshKanivu is right, try here. Commented Oct 1, 2013 at 12:30

1 Answer 1

3

Your function isn't preventing the form from submitting. To do that, you need to return false when you want the form submission to stop, and also use onClick="return myFunction()" to make sure it's passed correctly.

Note however that in up-to-date browsers you can just do this:

<input type="text" required />

The browser will automatically stop form submission if nothing was entered.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.