簡體   English   中英

防止表單提交不起作用,JavaScript

[英]prevent form from submitting not working, JavaScript

您好,謝謝您的寶貴時間。

我有一個帶有ID付款和一個提交按鈕的表單,但是我的JavaScript似乎有一個錯誤,因為我只收到警報消息,但是如果我輸入了錯誤的名稱(如一行井號),該頁面仍然會提交## #####。 以下代碼與我的文件中的代碼完全相同。

    // form validation, makes sure that the user inputs the correct data types.         

    function validateinput(event){

    var email = document.getElementById('email').value;
    var firstname = document.getElementById('firstname').value;
    var lastname = document.getElementById('lastname').value;
    var message = document.getElementById('message').value;

    var emailFilter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    var firstnameFilter = /^([" "a-zA-Z.-])+$/;
    var lastnameFilter = /^([" "a-zA-Z.-])+$/;
    var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;



    if (!emailFilter.test(email)) {
    alert('!Enter a email. Or enter a valid email address.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    }

    if (!firstnameFilter.test(firstname)) {
    alert('!Enter a first name. Or enter a valid name.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    }

    if (!lastnameFilter.test(lastname)) {
    alert('!Enter a last name. Or enter a name., only letters');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    } 

    if (!messageFilter.test(message)) {
    alert('!Enter a message.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    } 

    alert ('Your order was submited')

    }

    document.getElementById('payment').addEventListener("submit", validateinput)

還嘗試過其他方法,以為它們在此頁面上似乎不太起作用,但對其他人有用嗎?

就像更改var名稱和id一樣,在我的聯系頁面上使用的這一名稱

    function validateinput(event){
      var address1 = document.getElementById('address1').value;
    var postcode = document.getElementById('postcode').value;


    var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
    var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;

    var formValid = true;

    if (!address1Filter.test(address1)) {
    alert('!Enter an address. Or enter a valid address., only letters and   numbers');
    formValid = false;
    event.preventDefault();
    return false;
    }

    if (!postcodeFilter.test(postcode)) {
    alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
    formValid = false;
    event.preventDefault();
    return false;
    } 


    alert ('Your order was submited')

    }

    document.getElementById('payment').addEventListener("submit", validateinput)

那么我在做什么錯呢?

HTML

    <!doctype html>

    <!-- name: Edwin martin -date: 30/11/2015 -task:  a form  with split up inputs using the
    <fieldset> & <legend> tags -->

    <html lang="en">


      <head>
        <title>contact</title>
        <script type="text/javascript" src="scripts/contact2.js"> </script> 
            <!-- ensures the document is using the correct char set --> 
              <meta charset="utf-8">
              <meta name="description" content="contact page">  

              <link rel="icon" href="images/fav.png" type="image/png"/>

            <!-- 
                   The below section looks like a comment, but it's a conditional include statement.
                   It's ignored by all browsers except IE9.  html5shiv is a library that fixes some HTML5 
                   IE bugs. 
            -->

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


                  <!-- pulls in the styles sheet -->
              <link rel="stylesheet" href="styles/indexstyles.css">


      </head>


            <body onload="main()">


             <!-- start of the form, id form sets the position, size, border style and color -->
             <div id="form2">

                       <!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
                        <div id="head">
                            <header id="headcolor">
                                <div id="toplinks">
                                     <ul>
                                        <li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
                                        <li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
                                    </ul>
                                </div> <br>
                                       <br>
                            </header> 
                            <h1 id="title"> Contact </h1>
                            <p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
                        </div>

                        <div id="map"> </div>


                    <!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
                    <form id="payment">
                        <!-- Contact Information section --> 
                            <fieldset>  
                                <legend> Personal Information </legend> 
                                <p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname"  placeholder="enter a first name" class="add1"></p>
                                <p> <label> Last Name(*):   </label> <input type="text" name="last_name" id="lastname"  placeholder="enter a last name" class="add1"></p>
                                <p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
                                <p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
                                <p> <label> message(*):   </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
                            </fieldset>


                        <!-- Submit button --> 

                                <input type="submit" class="submit_button"> 
                                <input type="reset" class="reset_button"> 


                    </form>

            </div>
                <script type="text/javascript" src="scripts/contact.js"> </script> 

                 <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
        </body>
    </html>

我也有另一個JS腳本,您可以從兩個不同的鏈接中看到。 但是即使我刪除了該鏈接-那里的代碼仍然會以錯誤的輸入提交,因為此代碼只是讀取一個空輸入

 //onload callback function
 function main() {

 console.log("in main function");
  var myForm  = document.getElementById("payment");
  myForm.addEventListener("submit",validateForm);
}

 //validate callback function 
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment"); 

if (myForm.first_name.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("firstname").className += " formInvalid"; //add  the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.last_name.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.email.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.message.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 
}

document.getElementById('payment').addEventListener("submit", validateinput) ,問題是您想將參數傳遞給validateinput方法,但是您不能這樣做,無法將參數傳遞給回調方法參考,您應該將其包裝在這樣的匿名函數中。

document.getElementById('payment').addEventListener("submit", function(event) {
    validateinput(event);
});

我認為您已經使Java腳本復雜化了。 如果將提交更改為直接調用該函數,則可以更輕松地處理否定狀態。

<input type="submit" onclick="return validateinput();" class="submit_button">

您將需要稍微修改validateinput函數,因為您不再需要傳遞事件了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM