JavaScript: Why won't my form submit? - javascript

My problem is that my form, <form name="enrollment" method="post" action="submit.php"> will not submit. My submit button looks like: <input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />.
It calls this JavaScript function:
// Returns true if there are no errors and false if there are errors
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// No errors
return true;
}
// There are errors
alert("Errors exist in the form!");
return false;
}
The variable window.err_exist is defined in the function getReviewValues(). In getReviewValues(), I set window.err_exist = false;. Then, I validate the form with conditionals of the form:
// Name
var r_string = "Name: ";
if ( document.forms["enrollment"]["name"].value.trim() == "" ) {
r_string += "<span class=\"error\">This is a required field!</span>";
window.err_exist = true;
} else {
r_string += document.forms["enrollment"]["name"].value;
}
Then, at the end of getReviewValues(), I return r_string; for dynamic feedback on the status of the form validations. That is, messages like "Name: This is a required field!".
Now, if I fill out my form but leave some things blank so that I have validation errors, I get the alert "Errors exist in the form!" and the form doesn't submit. Great! However, when I fill out my form so that I have no validation errors, I do not get the error message. Great! But, oh no! The form still doesn't submit. And it should!
So, since I'm not getting the error message, then the execution path must be in the conditional if ( !window.err_exist ). I can see this because function then returns true so that the function never gets to send out the message. But, if it returns true, then my form should submit. So it must be returning false, since the form is not submitting. But if it's returning false, then the execution path cannot be in the assumed conditional. If that were the case, then I would get the message but I do not get the message. This is a contradiction.
Anyone have any ideas?

Instead of an "onclick" handler on your submit button, use the "onsubmit" event on your form element. For example:
<form onsubmit="return validate()">
At this point, as long as your validate method is returning true or false correctly... it should behave how you expect.
See http://www.w3schools.com/jsref/event_form_onsubmit.asp for a better reference.

When you validation is a success (window.err_exist != false) the script returns true. Thus you are returning true for a click event not a submit.
This could be fixed by doing what jeltine says <form onsubmit="validate()"> or it could be fixed by replacing the
<input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />
with
<input class="buttons" type="button" name="submit" onclick="validate()" value="Submit" />
Then changing the validate function to call form.submit(); on no errors.
EXAMPLE:
//must add id to get element by id
<form name="enrollment" id="enrollment" method="post" action="submit.php">
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// call submit on form
var myform = document.getElementById("enrollment");
myform.submit();
}
// There are errors
alert("Errors exist in the form!");
return false;
}
The advantage to doing it this way is that you have more control over changing form parameters such as action or method if needed. If these will not be needed then just change to onsubmit="".

Related

calling a method if the validation function is true

When the submit button is pressed, my validation function should check if the fields are validated then call the setProfile method. currently when i click the submit button it will not validate my fields so something must be wrong
<form name="Login" method="post" action="#" onsubmit="return validateForm()">
<input type="text" name="fName" id="name"> <br>
</form>
<input type="submit" name="Update" value="Update">
function validateForm() {
var n = document.forms['Login']['fName'].value;
if(n==null || n=="")
{
alert("Please enter your name");
return false;
}
return true
}
function UpdateProfile() {
document.querySelector('submit').addEventListener('click', e=>{
const myProfile = new Profile
if (e.validateForm === true){
myProfile.setProfile();}
})
}
The most likely reason for your code not working is that your validateForm() function is not getting called at all on submit button press. To find out if that's the case, the simplest thing to do is to add an alert() at the top of the validateForm() function.
If it's indeed not called, google "call javascript function on button click" for a code sample. Here's one: Using an HTML button to call a JavaScript function

Stopping submitting when alert is shown

I have form that has text input and submit. I'm trying to show an alert with Javascript if input is empty.
This is my code:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
function emptyArea() {
if (document.getElementById("type-text").value.trim() == '') {
alert("Please fill all fields");
} else("OK");
}
<form>
<input id="type-text" type="text" placeholder="Type some text">
<input type="submit" placeholder="Submit" onclick="emptyArea()">
</form>
When I click submit and it is empty, form still submits and doesn't show the alert. How would I prevent it from submitting and instead show an alert?
When I run your code, I actually do get alerts when I click "submit". Are you sure you are attaching the event handler correctly? I'm guessing maybe what's actually happening is that the alert is showing but then it submits anyway no matter if the form value is valid.
If you want to prevent the form from submitting, call e.preventDefault() where e is the event object which will be passed as the first argument to your handler function.
Here is an example codepen:
https://codepen.io/quinnfreedman/pen/PoqmGYb
function emptyArea(e) {
if (document.getElementById("text").value.trim() == '') { // .trim is supported by browsers since IE9
alert("Please fill all fields");
// the conditions were not met, so call preventDefault to
// stop the browsers default behavior of submitting the form
e.preventDefault();
e.stopPropagation();
} else {
// If we don't preventDefault, the form will submit after this alert
alert("OK")
}
}
document.getElementById("Submit").addEventListener("click", emptyArea)
<form action="#">
<input type="text" id="text" />
<input type="submit" id="Submit" />
<!-- NEVER call anything "submit" in a form -->
</form>

prevent form submission (javascript)

I have a form with a text input:
<form name="form1">
<cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>
I only want it to submit in certain cases. (I run some error-checking first)
<script>
function someFunc() {
if (1==2) {
document.form1.submit();
} else {
alert("Not submitting");
}
</script>
The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).
Many thanks if anyone can shed some light on this . . .
There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.
The basic way to approach this is like so:
<form name="form1" onsubmit="return someFunc()">
<input type="text" name="text1" id="text1">
</form>
When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.
Now your JavaScript needs a slight alteration:
<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.
EDIT: Documentation on implicit form submission.
EDIT 2:
This code:
$(document).ready(function(){
$("#text1").on('change', function(event){
event.preventDefault();
});
});
is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
});
});
Which would allow you to do something like this:
$(document).ready(function(){
$("#form1").submit(function(event){
if ( $('#text1').val() !== "foo" ) {
alert("Error");
event.preventDefault();
}
});
});
var form = document.getElementById("Your Form ID");
form.addEventListener("submit", function (e) {
if ("Your Desired Conditions.") {
e.preventDefault();
}
});
use the following code it will work perfectly fine
<form onsubmit="return false;" >

After onclick no error detect but cannot post into my database

this is my form name
<form name="form" id="form" method="post">
this my onclick
<input type="submit"
name="submit"
value="Register"
onclick="return validate()" />
this is my validate()
function validate()
{
var f = document.forms['form'];
var ary=[checkfname,checklname,checkEmail,checkAge,checkAdd,validtp,validhp,checkName,validpass];
var rtn=true;
var z0=0;
for (var z0=0;z0<ary.length;z0++)
{
if (!ary[z0](f))
{
rtn=false;
}
}
return rtn;
}
i think is my validate return there cannot return to post
hope someone can help me to solve the problem,thx...
Looks like you are storing an array of functions that make different validations:
var ary=[checkfname,checklname,checkEmail,checkAge,checkAdd,validtp,validhp,checkName,validpass];
Then you iterate that array and each function is executed receiving the form as parameter.
!ary[z0](f)
If you return false, the default action will be prevented, in this case the form won't be submitted.
So I'm pretty sure one of your validations is returning false. You should check each one of those functions and see wich one is returning false - you could debug using tools such as chrome dev tools or firebug.

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

Categories