简体   繁体   English

表单验证无效-JavaScript

[英]Form Validation not working - javascript

I am trying to implement form validation so that when the submit button is hit, all required fields are filled. 我正在尝试实施表单验证,以便在单击“提交”按钮时,将填写所有必填字段。 here is my code: 这是我的代码:

function checkInput()
{
    <!--check if these input values are provided -->
    var inputFile = document.getElementByID('inputFile').value;
    var numThreads = document.getElementById('numThreads').value;
    var scoreThresh = document.getElementById('scoreThresh').value;
    var scorePen = document.getElementById('scorePenalty').value;

    if(inputFile==="" ||numThreads==="" ||scoreThresh==="" ||scorePen==="" )
    {
        alert('Please fill in all required fields');

    }

//how i decalare the form //我如何贴花表格

 <form  method =POST id="weVoteForm" onsubmit="return checkInput()">

this code isnt working however. 此代码不起作用。 Can anyone clarify what is wrong? 谁能澄清出什么问题了? Thanks! 谢谢!

You need to call the checkInput function before submitting the form. 您需要在提交表单之前调用checkInput函数。 For this you can use onsubmit event in the form element as. 为此,您可以在form元素中使用onsubmit事件。

<form method="POST" id="weVoteForm" onsubmit="return checkInput();">
</form>

Your function should look like this 您的功能应如下所示

function checkInput()
{

    //check if these input values are provided -->
    // notice not <!-- in JS for comment and Id not ID
    var inputFile = document.getElementById('inputFile').value;
    var numThreads = document.getElementById('numThreads').value;
    var scoreThresh = document.getElementById('scoreThresh').value;
    var scorePen = document.getElementById('scorePenalty').value;

    if(inputFile==="" ||numThreads==="" ||scoreThresh==="" ||scorePen==="" )
    {
        alert('Please fill in all required fields');
        return false;
    }
  return true;
}

Moreover you can set required attribute in each element without having you to write this code as. 此外,您可以在每个元素中设置必填属性,而无需编写此代码。

<input type="text" required />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM