Show me a Simple javascript onSubmit handler

后端 未结 4 392
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 18:01

Hello again everyone i am working on this



        
相关标签:
4条回答
  • 2021-01-19 18:24

    OnSubmit is invoked once for the form.

    You can validate all the form fields in one onSubmit function, during one call to that function.

    function myOnSubmitHandler(theForm) { 
        if (theForm.data1.value == "") { 
            alert("This field is empty.");
            return false; // suppress form submission
        } else {
            return true; // A-OK, form will be submitted
        }
    }
    

    in HTML:

    <form method="POST" ACTION="SomethingOnServer.php" 
          onSubmit="return myOnSubmitHandler(this);">
    
    0 讨论(0)
  • 2021-01-19 18:32

    I need to have a onsubmit form handler

    You said it; <form onsubmit="return myValidate(this);" .... >

    myValidate is your validation function that returns true|false indicating whether or not you want the form to be submitted to its handler script (which your also missing).

    0 讨论(0)
  • 2021-01-19 18:42

    I've added an example here of how to do it:

    http://jsfiddle.net/tomgrohl/JMkAP/

    I added an onsubmit handler to the form:

    <form method="post" action="javascript" enctype="text/plain" onsubmit="return valForm(this);">
    

    And added this at the top of the page, a simple validation function:

    <script type="text/javascript">
    function valForm( form ){
    
        var firstVal, lastVal, emailVal, error = '';
    
        firstVal= form.first.value;  
        lastVal= form.last.value;
        emailVal= form.email.value;
    
        //OR
        //firstVal= document.getElementById('first').value;  
        //lastVal= document.getElementById('last').value;
        //emailVal= document.getElementById('email').value;
    
        if( firstVal.length == 0){
            error += 'First name is required\n';
        }
    
        if( lastVal.length == 0){
            error += 'Last name is required\n';
        }
    
        if( emailVal.length == 0){
            error += 'Email is required\n';
        }
    
        if( error ){
            alert( error );
            return false;
        }
    
        return true;
    }
    </script>
    
    0 讨论(0)
  • 2021-01-19 18:43

    might I suggest you use jQuery and jQuery validate to validate your form no need to re-invent the wheel

    be sure to check out validator's demo

    0 讨论(0)
提交回复
热议问题