首页 > 解决方案 > prevent form submission if form fields are not filled

问题描述

I have this code

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<form name="myForm" action="/action_page.php" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

I don't want user to submit if field is not filled

标签: javascript

解决方案


我接到你了

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

推荐阅读