如果未填写表单字段,则阻止提交表单

时间:2018-07-11 13:53:22

标签: javascript

我有这个代码

AdaBoostClassifier(base_estimator=DecisionTreeClassifier(),n_estimators=400,learning_rate=0.01,algorithm='SAMME')

如果字段未填写,我不希望用户提交

3 个答案:

答案 0 :(得分:0)

我懂了你

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

答案 1 :(得分:0)

检查此:

let form = document.forms['myForm'];
let input = form.querySelector('input[name="fname"]');
form.addEventListner('submit',(e) => {
  if(!input.length){
    e.preventDefault():
  }
})

答案 2 :(得分:0)

您可以直接在输入字段中使用Html5 required属性,因此您的代码段将变为:

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

来源:https://www.w3schools.com/TAgs/att_input_required.asp