简体   繁体   中英

looping through an html form

I'm trying to validate the html form and return an alert if any of the elements are empty on submission. When I test this script, the from is sent to the server regardless whether any of the fields are filled in. Any help will be appreciated.

<script type="text/javascript">
    /* <![CDATA [ */

        function validateForm()
        {
            for(var i=0; i < document.salesRecords.elements.length; i++)
            {
                if(document.salesRecords.elements[i].value == null || document.salesRecords.elements[i].value == "")
                {
                    alert("Error " + name + " must be given a value");
                    return false;
                }
                else return true;
            }
        }

    /* ]]> */   
    </script>

HTML

<form action ="some_action.php" name="salesRecords" method="post">
Client = <input type="text" name="client" value="" /> </br>
Date = <input type="text" name="date" value="" /> </br>
Value = <input type="text" name="amount" value="" /> </br>
<input type="submit" value="Submit" onclick="validateForm();"/>

Try this:

<input type="submit" value="Submit" onclick="return validateForm();"/>

function validateForm()
    {
        for(var i=0; i < document.salesRecords.elements.length; i++)
        {
            if(document.salesRecords.elements[i].value == null ||
             document.salesRecords.elements[i].value == "")
            {
                 alert("Error " + document.salesRecords.elements[i].getAttribute("name") + " must be given a value");
                return false;
            }

        }

    }

In your Submit button's onclick attribute, you have to actually use the return value with return validateForm(); , not just call the method:

<input type="submit" value="Submit" onclick="return validateForm();"/>

UPDATE (additional logic issue in the javascript)

After looking at your javascript, you have a logic issue that will cause the form to submit even when some fields are "not valid":

else return true;

This line is inside your for loop and will return true after the very first form-field validates properly.

The fix is to simply remove the line and add return true; after the loop finishes:

function validateForm() {
    for(var i=0; i < document.salesRecords.elements.length; i++) {
        if(document.salesRecords.elements[i].value == null || document.salesRecords.elements[i].value == "") {
            alert("Error " + name + " must be given a value");
            return false;
        }
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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