BUN
BUN

Reputation: 57

Validate on submit button got issue

Here is my code example

<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submitForm();">

Below is my function

<script type="text/javascript">
    function submitForm()
    {
   var name = document.getElementById("name").value;
       return false;
    }
</script>

On press, the form still submit, but if i change

onsubmit="return false;"

then the form won't submit, how do I use the function to return false as i need do some if else validation

Upvotes: 2

Views: 77

Answers (3)

omikes
omikes

Reputation: 8513

I like to make an invisible button for the actual submit which is only triggered after form validation:

function validate() {
    var valid = true;
    $.each($('input'), function(){
        valid = valid && $(this).val().length > 0;
    })
    if (valid) {
        $('#realSubmit').click();
    } else {
        alert('Please fill out all fields!');
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submit();">
    <input type="text" placeholder="Enter Name" />
    <input type="password" placeholder="Enter Password" />
    <button type="button" onclick="validate()">Submit</button>
    <button type="submit" id="realSubmit" style="display:none"></button>
</form>

Upvotes: 0

vol7ron
vol7ron

Reputation: 42099

<script type="text/javascript">
  function submitForm() {
    return false;
  }
</script>

<form 
   action="next2.php" 
   method="post" 
   name="next2" 
   id="next2" 
   onsubmit="return submitForm();"
 >

submit is already a function for the form, you should call your JavaScript function something different, for instance submitForm as in the above.

Upvotes: 2

Manoj Krishna
Manoj Krishna

Reputation: 800

just remove the semicolon in your function and place a alert in your function to make sure whether the function is called first.and then try to add validation

Upvotes: 0

Related Questions