Javascript function fires twice on clicking 'Submit' button - javascript

I'm trying to insert records into DB using AJAX. I'm not sure why, but it seems the javascript function referenced in the onclick tag of the submit button gets fired twice, and hence I get two records in my DB per click.
Placing alerts in the JS, I have managed to figure out that the problem is in the JS function getting called twice, and not the PHP script making two inserts. So, I'm not posting the PHP script, unless asked.
Here's the HTML for the form:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}

You are calling processInfo twice once in submit handler and once in click handler. This might be the reason.
Here onclick="processInfo()" and inside
$("#notify").submit(function() {
processInfo();
return false;
});

processInfo() is called twice, both here, when the form submits:
$("#notify").submit(function() {
processInfo();
return false;
});
and here, when you click the submit button:
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
You should remove one of them.

You are calling the processInfo() function twice: once on the form submit event, and once on the onclick on the input.
You should only attach the processInfo() function on the submit event. Remove the onlick dom0 event handler (inline scripts are to be avoided).
Also, do not use return false; as it prevents event bubbling. Use ev.preventDefault() instead.
$("document").ready(function() {
$("#notify").submit(function(ev) {
ev.preventDefault();
processInfo();
});
});

Related

Submit form after unbinding

$("#qwerq").submit(function (e){
e.preventDefault();
var check=0;
if($("#firstName").val() == "") {
check=1;
}
if(check!=1){
$("#qwerq").unbind("submit") ;
$("#qwerq").submit();
//$("#qwerq").trigger('submit', [true]);
}
});
When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.
I have tried using .submit() and .trigger("submit"). I have to manually click on submit again.
What should I add so that I don't have to click again?
Instead of unbinding the events, why won't you just prevent submitting only on error?
if(check === 1) return false;
return false in jQuery's event handler means preventDefault and stopPropagation.
I think you were trying to submit a form on a button click.
Then you need to make some changes in your code:
Provide an id to your form and change button type="button" (instead of "submit"):
<form id="form_1" action="yourserverpagename.php" method="post">
<input id="firstName" type="text" value="" />
<input id="qwerq" type="button" value="Send" />
</form>
Now your script should like below:
<script>
$("#qwerq").click(function (e) {
e.preventDefault();
var check = 0;
if ($("#firstName").val() == "") {
check = 1;
}
if (check != 1) {
//-- here is the way to submit the form using form id --
$('#form_1').submit();
}
});
</script>

JavaScript: add latest form event

I'm writing a plugin and like to add a function to a submit/onsubmit event, that should only fire if all existing submit/onsubmit events return true.
It is ensured that my javascript-file will be loaded at last, but I have no idea if there is already a listener on the submit event (e.g.from another plugin).
Let's assume I have this form:
<form action="" method="POST" onsubmit="return validateForm()" id="dummyform">
Mandatory field:<br>
<input type="text" name="required" id="required" value="">
<br><br>
<input type="submit" value="Submit" class="placeOrder">
</form>
the on submit-Event validates the form and maybe there are some other events listening on the submit event. The validate form could look like this:
function validateForm() {
var x = document.getElementById('required').value;
if (x == "") {
alert("required fields must be filled out");
return false;
}
return true;
}
Is there a way to ensure all existing listeners are executed and only if all return true, execute my function?
I tried something like this:
var classname = document.getElementsByClassName("hook");
Array.from(classname).forEach(function(element) {
let form = findParentForm();
bindEvent(form, 'submit', function(e){
e.preventDefault();
if(form.onsubmit() === false)
return false;
modal.style.display = "block";
return false;
});
});
BindEvent is just a function to support IE8. It does a element.addEventListener(eventName, eventHandler, false); or element.attachEvent('on' + eventName, eventHandler);

validate mobile number in javascript

I want to validate my mobile number using javascript and my code is:
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
and calling function is:
<input type="text" name="Contact-No." id="textbox" required >Contact(Mobile No.)
<input type="submit" value="Submit" onclick="checkLength()">
All works fine but after showing alert message it should be return on same page but it takes me to some other blank page.
remove the onClick event from button and add onSubmit to <form..>.
Something like <form onSubmit='return checkLength();>'.
1) Your form needs to prevent the default submit action so that if you find error the form doesnt actually submit.. you should hook into the onsubmit event in your form.
an example assuming you've included jQuery 1.7+ on the page
html
<form id="myform" action="/">
<input type="text" name="Contact-No." id="textbox" />
Contact(Mobile No.)<br><br>
<input type="submit" value="Submit" id="submit" />
</form>
javascript
$("#myform").on("submit",function(e){
if(checkLength()==false){
alert('prevent form submit');
e.preventDefault();
}else{
alert('form submits as normal');
}
});
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
return true;
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
example at:
http://jsfiddle.net/Lqbn6unp/
As pointed out elsewhere, the listener should be on the form's submit handler since the form can be submitted without pressing the submit button. Also, you can reference form controls as named properties of the form, which is more efficient than using getElementById and means the control doesn't need an ID.
So pass a reference to the form from the listener, e.g.
In the form:
<form onsubmit="return checkLength(this)" ... >
<input type="text" name="Contact-No." required >Contact(Mobile No.)
then in the function:
function checkLength(form) {
var textbox = form['Contact-No'];
if (textbox.value.length == 10) {
alert("success");
} else {
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

JavaScript Form Validation when false

This is really bothering me. I just want the form to not submit if the function returns false. Here is the script.
function checkPass(){
var pass1 = document.getElementById('pass');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirmMessage');
var goodColor = "#224466";
var badColor = "#900000";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
return true;
}else{
pass2.style.backgroundColor = badColor;
return false;
}
}
The form still submits when I use:
<form onsumbit="checkPass();">
</form>
and when I use:
<form>
<input type="submit" onclick="checkPass();">
</form>
and no luck. Any ideas?
Use this on the onsubmit event of your form:
onsubmit="return checkPass()"
Or this one for your Submit button (the input tag):
onclick="return checkForm()"
If you are using xhtml make sure 'onsubmit' is lowercase.
<form onsubmit="return checkPass()" ... >
As M2X says, you need to use
<form onsubmit="return checkPass();">
The reason is that when you assign an event handler as an attribute that way, what actually happens internally is that a new anonymous function is created wrapped around the code in the attribute, and that function needs to return the value that will prevent or allow the form submission.
So your original onsubmit attribute will be turned into:
function() {
checkPass();
}
which executes the checkPass function but discards its return value. By including the return in the attribute, it will be turned into:
function() {
return checkPass();
}
which will return the value returned to it by the checkPass function, thereby achieving the desired effect.

Categories

Resources