Javascript表单验证onclick按钮没有错误但也不起作用

标签 javascript jquery forms validation onclick

所以标题几乎说明了一切。 validateForm 函数是我遇到问题的函数。我试图检查是否尚未输入某个字段,然后在那里发布一条消息(span 标记),但我使用 css 隐藏它。所以我想要隐藏的跨度标签来显示输入字段之一是否未被触摸。我有处理名字、姓氏、电子邮件和电话号码的功能。我还将验证 validateform 函数中的复选框和文本区域。由于这是一个相当大的网站,一些代码将不会显示。但如果您能发现错误,我将不胜感激。

<!DOCTYPE html>
<html lang="en">

<head>
    <title>NONEYA</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!--[if lt EI 9]>
    <script src= "http://html5shim.googlecode.com/svn/trunk/html5.js">
    </script>
    <![endif]-->

    <link rel="icon" href="images/hammerFavicon.ico" type="image/gif">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href = "css/custom/siteStyle.css">

    <script src="js/main.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" ></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" "></script>
</head>

<body>

    <!-- Header include -------------------------------------------------------------------------------------- -->
    <?php include("includes/header.php"); ?>

    <!-- Navigation include ---------------------------------------------------------------------------------- -->
    <?php include("includes/navigation.php"); ?>

    <!-- Main Content section -------------------------------------------------------------------------------- -->
    <main role="main" class="container">

        <!-- The Modal -->
        <div id="myModal" class="modal">

            <!-- Modal content -->
            <div class="modal-content">
                <span class="close">&times;</span>
                <p>Is this information correct?</p>
                <div class="myButton">
                    <input type="submit" value="Yes" class="btnSize"/>
                    <input type="button" value="No" class="btnSize"/>
                </div>
            </div>
        </div> 

        <div class="jumbotron">

            <!-- Paragraph for text if needed ---------------------------------------------------------------- -->          
            <p class="lead">

                <h2>Ask Us A Question</h2>
                <br />
                <!-- Question submission form ---------------------------------------------------------------- -->
                <form action="" onsubmit="return validateForm()">


                    <div class = "fiftypercentofwidth">

                        <!--- First Name ------------->
                        <div class="form-group">
                            <div class="col">
                                <label for="fN">First Name</label>
                                    <input type="text" onblur="validateFName(fN)" class="form-control" placeholder="First Name" id="fN">
                            </div>
                        </div>
                        <!--Last Name -------------->
                        <div class="form-group">
                            <div class="col">
                                <label for="lN">Last Name</label>
                                    <input type="text" onblur="validateLName(lN)" class="form-control" placeholder="Last Name" id="lN">
                            </div>
                        </div>

                        <!-- Email -->
                        <div class="form-group">
                            <div class="col">
                                <label for="eMail">Email</label>
                                    <input type="text" onblur="validateEmail(eMail)" class="form-control" placeholder="Email" id="eMail">
                            </div>
                        </div>
                        <br>

                        <!-- Phone Number -->
                        <div class="form-group">
                            <div class="col">
                                <label for="phoneNumber">Phone number</label>
                                    <input type="text" onblur="validatePhoneNum(phoneNumber)" class="form-control" placeholder="Phone number" id="phoneNumber">
                            </div>
                        </div>
                        <br>

                        <!--Client Question Topic----------------------------------------------------------------------->
                        <h5>Select Question Category</h5>
                        <div class="form-group form-control">
                            <select id="qCategory">
                                <option disabled selected value>select an option</option>
                                <option value="Family Law">Family Law</option>
                                <option value="Housing Issues">Housing Issues</option>
                                <option value="Landlord/Tennant">Landlord/Tennant</option>
                                <option value="Social Security & Other Benefits">Social Security & Other Benefits</option>
                                <option value="Consumer Law">Cosnumer Law</option>
                                <option value="Education Law">Education Law</option>
                                <option value="Elder Law">Elder Law</option>
                                <option value="Immigration">Immigration</option>
                                <option value="Veterans">Veterans</option>
                                <option value="Post-conviction Issues">Post-Conviction Issues</option>
                                <option value="Driver&#39s License/Id Issues">Driver&#39s License/ ID Issues</option>
                                <option value="Criminal Law">Criminal Law</option>
                                <option value="Probate Matters">Probate Matters</option>
                                <option value="Estate Planning">Estate Planning</option>
                                <option value="Small Business Development">Small Business Development</option>
                            </select>

                            <br><br>                    

                            <!-- Client Question Details text field ------------------------------------------------------ -->
                            <h5>Enter your question:</h5>
                            <div class="form-group">
                                <textarea class="form-control" rows = "6" cols = "65"></textarea>
                            </div>
                            <br>    
                        </div>
                        <br>

                        <div>
                            <span id="formError">Please Fill in Entire Form</span>
                            <button onclick="validateForm()" class="button button-block" id="cTModal">Create Ticket</button>
                        </div>
                    </div>
                </form> 
            </p>
        </div>
    </main> 

    <!-- Footer include ---------------------------------------------------------------------------------------->
    <?php include("includes/footer.php"); ?>

    <!--Popup validation----------------------------------------------------------------------------------------
    <script>
    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("cTModal");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
    </script>   
    ---------------------------------------------------------------------------------------------------------->

</body>

</html>


**BEGINNING OF MY JAVASCRIPT CODE**

//Checks if user has pressed update without entering fields
function validateForm(){

    if($('fN').innerHTML == ''){
        $('formError').style.display = 'block';
        return false;
            } else if ($('lN').innerHTML == ''){  
                $('formError').style.display = 'block';
                return false;
                    } else if ($('eMail').innerHTML == ''){
                        $('formError').style.display = 'block';
                        return false;
                            } else {
                                $("formError").hide();
                                return true;
                            }
}   



function validateFName(x){
    var re = /[a-zA-Z]$/;

    if (x.value == ""){
        x.style.background = '#e35152';
        x.style.color = 'white';
        x.value = "Please Fill in First Name";
        return false;   
            } else {
                if (!re.test(x.value)){
                    x.style.background = '#e35152';
                    x.style.color = 'white';
                    x.value = "Please Use Only Letters";
                    return false;
                        } else {
                            x.style.background = 'white';
                            x.style.color = 'black';
                            return true;
                            }
                }
}

function validateLName(x){
    var re = /[a-zA-Z]$/;

    if (x.value == ""){
        x.style.background = '#e35152';
        x.style.color = 'white';
        x.value = "Please Fill in Last Name";
        return false;   
            } else {
                if (!re.test(x.value)){
                    x.style.background = '#e35152';
                    x.style.color = 'white';
                    x.value = "Please Use Only Letters";
                    return false;
                        } else {
                            x.style.background = 'white';
                            x.style.color = 'black';
                            return true;
                            }
                }
}

function validateEmail(x){
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (x.value == ""){
        x.style.background = '#e35152';
        x.style.color = 'white';
        x.value = "Please Fill in Email";
        return false;   
            } else {
                if (!re.test(x.value)){
                    x.style.background = '#e35152';
                    x.style.color = 'white';
                    x.value = "You must enter a valid Email";
                    return false;
                        } else {
                            x.style.background = 'white';
                            x.style.color = 'black';
                            return true;
                            }
                }   
}


function validatePhoneNum(x) {
    var re = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

    if(x.value == "") {
        x.style.background = '#e35152';
        x.style.color = 'white';
        x.value = "Please enter phone number xxx-xxx-xxxx";
        return false;
            } else {
                if (!re.test(x.value)){
                    x.style.background = '#e35152';
                    x.style.color = 'white';
                    x.value = "Please enter phone number xxx-xxx-xxxx";                 
                    return false;
                        } else {
                            x.style.background = 'white';
                            x.style.color = 'black';
                            return true;                            
                        }
    }
}

最佳答案

使用.value(而不是.innerHTML)获取输入元素的值。另外,要按 ID 选择,您需要在字符串前添加“#”。 (此外,最好选择严格平等而不是松散平等)

您还可以按照 DRY 清理一些代码。示例:

function validateForm() {
  const inputIDs = ['fN', 'lN', 'eMail'];
  const formError = document.querySelector('#formError');
  if (inputIDs.some(inputID => document.getElementById(inputID).value.length === 0)) {
    formError.style.display = 'block';
    return false;
  } else {
    formError.style.display = 'none';
    return true;
  }
}

关于Javascript表单验证onclick按钮没有错误但也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374043/

相关文章:

javascript - mvc 和 ajax - 未命中模型属性

javascript - 用于自动填写 Angular 创建的用户密码表单的内容脚本

javascript - 使用 jQuery 显示/隐藏 <div>

javascript - 重叠的矩形 JavaScript

javascript - 跟踪 onclick 操作

javascript - 不使用 event.preventDefault 阻止 html5 表单提交

javascript - 通过纯 JS 提交时,查询表单提交不会触发

javascript - 为什么这个简单的内容 slider 不起作用?

javascript - 使保存按钮在编辑后起作用

jQuery Mobile 动态添加元素