Validate on submit button got issue - javascript

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

<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.

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

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>

Related

How to avoid onsubmit="return validateForm()" to submit the form when the validateForm() have a bug?

How to avoid onsubmit="return validateForm()" to submit the form, when the validateForm() have a bug?
<form action="index.php" method="post" name="eform" onsubmit="return validateForm();">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>
<script>
function validateForm() {
if (dosomething) {
return true;
} else {
return false;
}
}
</script>
But when function validateForm() have some code error, such as...
function validateForm() {
ifffffffffffff(dosomerthing) { // Creates an error
return true;
} else {
return false;
}
}
The form is submitted automatically...
It displays 1 sec in Chrome console, how can I avoid this???
Thank you very much!
Update:
var from = document.getElementById('form');
form.addEventListener('submit', validateForm);
function validateForm(event) {
try {
error
} catch(err) {
console.log(err);
event.preventDefault();
}
}
<form action="index.php" method="post" name="eform" id="form">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>
If I understand your question correctly you want to execute or stop executing the form method with an condition?
if so take a look, it may help you to get going.
function validateForm() {
var val ="errrrr"; // place your error here.
if(val == "err")
{
alert("submit form");
}
else
{
alert("don't submit the form"); //do what you want to do.
}
}
<form action="index.php" method="post" name="eform" onsubmit="return validateForm();">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>

onclick="validateForm();return false"?

I came across some code involving a submit button, whose onclick attribute is: onclick="validateForm();return false". For example:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
}
else
document.myForm.submit();
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit" onclick="validateForm();return false">
</form>
</body>
</html>
I don't see any difference even if I remove return false in the above example. The return false does not stop the form from submitting as long as the text field is entered. So, what's the purpose of using "return false" immediately after the form is submitted by document.myForm.submit()?
It’s for when the form isn’t submitted by document.myForm.submit(), i.e. in the error case. A better way to write it would probably be to have validateForm control the return value:
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
// Error; cancel the form submission
return false;
}
// Just let the browser continue submitting; no need to .submit()
return true;
}
and
<form name="myForm" action="formHandler.jsp" method="post" target="_blank"
onsubmit="return validateForm()">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit">
</form>
Check Working example :
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

How to validate input using external javascript?

Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?
HTML
<div data-role="page" id="page1">
<div data-role="header">
Back
<h2>Add New</h2>
</div>
<!-- main -->
<div data-role="main" class="ui-content">
<form name="myform" onclick="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>
</div>
<!-- footer -->
<div data-role="footer">
<h2>mine</h2>
</div>
</div>
Code from external javascript
function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
Use onsubmit, and by passing this from the event handler, you can use it instead for document.forms[....]
HTML
<form name="myform" onsubmit="return validateForm(this)" method="post">
Script
function validateForm(theform){
var x = theform["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
And by using event listeners it can be even more maintainable (and unobtrusive)
HTML
<form name="myform" method="post">
Script
window.addEventListener('load', function() { /* fires when page been loaded */
document.querySelector('[name="myform"]').addEventListener('submit', function(e) {
var x = e.target["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
});
});
You should use the onchange event because onclick triggers before having a chance to actually write something in the input.
This way you can deal with the validation after the value has changed and not wait for the form to be submitted.
Or if you want to validate just before submit you can use the onsubmit event like LGSon suggested.
function validateForm() {
var x = document.forms["myform"]["myname"].value;
if (x == null || x == "") {
alert("enter name");
return false;
} else {
console.log(true, x);
return true;
}
}
<form name="myform" onchange="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name">
<button type="button" id="but_submit">Submit</button>
</form>
Use below html code:
<form name="myform" onsubmit="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>

JavaScript custom validation not working

Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}

Form gets submitted even if JavaScript fun returns false

Pls check code .html form gets submitted even if javascript returns false.
<form id="form1" name="form1" method="post" action="sub.jsp" onsubmit="return getValue()">
<input type="text" id="userName" name="userName" onkeyup="return getValue()" />
<input type="submit" name="Submit" value="Submit" />
</form>
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
form.userName.focus();
return false;
}
return true;
}
1) try changing line form.userName.focus(); to document.form1.userName.focus();
OR
2) try submitting from function itself:
<input type="button" name="Submit" value="Submit" onclick="getValue()" />
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
document.form1.userName.focus();//I think this is the problem
return false;
}
document.form1.submit();
}
</script>
I think there are errors in your JavaScript code that happen prior to your return statements. Fix those errors and your code should work.
alternatively, you make the click handler on the submit button to return false.

Categories