JavaScript alternatives to HTML submit-button, due to JS conflict - javascript

I've created a page in which I use a JavaScript validator on the input fields (using a script from javascript-coder.com), but I can't use my to submit the form, because it's conflicting with a function the validation script is using. My current submit button:
Submit
When i use a standard HTML submit button, the script works fine. Is there any other way or function to submit the form without conflicting with the validation script? I'm not confident enough in JS to begin taking the validation script apart.
Please help, and please ask if you need any additional info.
Thanks,

If that is your actual code, you are using the this keyword incorrectly. When called from an inline function, this refers to the element is is being called from, i.e. the anchor tag. (See here for more details: http://www.quirksmode.org/js/this.html.) As far as I am aware, you need to submit the form from the form tag.
What you should be using is something like one of these:
document.getElementById('myForm').submit();
document.forms[0].submit();
document.getElementsByClassName('submit')[0].submit(); /* not IE8 compatible */
Alternatively, if you cannot rely on your element having an ID tag, being in a known order on the page and you require IE compatibility, you could continue searching "up" the DOM until you find the form that the button sits in, then submit that:
var parentelem = this.parentNode;
while (parentelem.nodeName.toLowerCase() != 'form') {
parentelem = parentelem.parentNode;
if (parentelem == null) { break; }
}
if (parentelem != null) {
parentelem.submit()
}

Try this
Submit

The validation script uses the onsubmit event of the form to trigger the validations. When you submit the form programatically, the event does to get fired. This should work:
Submit
where yourform is the ID of your form. See this page for details:
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml

Related

How to handle Ajax-generated form in Javascript?

So I use this Javascript to handle forms:
$(':submit:not(.form-default-submit)').click(function(event) {
//Disable normal form submission, handle using ajax
});
It works correctly in most cases. So any submit element with the class form-default-submit is ignored, and all others are handled in this Javascript.
But I've just noticed that this doesn't work for Ajax-generated content. Which I'm guessing is because this code is run on page load, before the Ajax content is loaded.
I see people using:
$(document).on("click", selector, function(e){
As a fix for this. But in my case, I don't just apply it to the element directly. I have that condition to allow exceptions for elements with the class form-default-submit.
Is the only way to do this with the new Ajax-supported method to have an if statement within the function checking if the element has a particular class? Or can I do this within the selector itself? This is a bit above my current ability, so thanks for any help!
Try this:
$(document).on( "click",":submit:not(.form-default-submit)", function(e){
You can bind the submit event directly to the form and return false. This will also catch a form sent by using the enter key.
$("#form").on("submit", function(event){
// Send form data by AJAX
$.post(...);
// Prevent form to be sent the regular way
return false;
});

Yii and Javascript form submission

I'm using Yii as a PHP framework for my site. Additionally, my site uses some js/jquery like, say, a jQuery UI Dialog widget (except for those dialogs, the rest of the code is pure normal html form components and jQuery code for the event handlers).
In the Yii side, I use CForms to build my forms from specifications file.
When I test if the form was submitted, I must do it for a certain button. This is not only forced, but I also take advantage of it.
if ($myCFormInstance->submitted('approve')) {
//process approval code
} else if ($myCFormInstance->submitted('reject')) {
//process rejection code
}
The actual problem I have is a bit conceptual one, since -fortunately- I know what's going on with my code and -again, fortunately- know the problem root:
Somewhere in My code I intercept the submit button's click event:
$(function(){
$(".critical-action").click(function(e){
var form = $(this).closest("form");
e.preventDefault();
e.stopImmediatePropagation();
confirmDialog("¿Continuar?", "#critical-action-dialog", function(){
form.submit();
});
});
});
Say the .critical-action classed elements are always a submit button in a form.
The intention of the code: cancel the form submission, and perform it only if the user -in the dialog- clicks the "Yes, Continue" (i.e. confirming the action) button.
This code works as expected, and have no problems at a javascript level BUT -and here goes my issue- when doing form.submit(), the button is not sent as part of the form. This is obvious: I'm sending the form without specifying any button. In the case of Approve and Reject, which have two buttons, the example explains itself: if the form.submit() call could send their buttons ¿which of them should send?.
Question: So, since form.submit() doesn't send any button, but I actually need buttons ¿how can I send the form "with the corresponding button" -i.e. a button I choose to specify, which should correspond to this in the click handler function context- automatically via javascript? The button NEEDS to be identified by Yii in order to process the form (specially with the Approve and Reject case).
If you added a hidden input to the form, you can modify the input value with jQuery before you submit the form, like this:
$("#inputID").val('approve');
If you want to set the value to the value of the clicked button via $(this).val(), be aware of the issue that could result in an IE browser, explain here. The second answer (by postpostmodern) has a solution to this issue.

Preventing multiple form submits

I am submitting a form using JQuery and an event listener bound to a div (not an input field) and I am trying to prevent multiple submits, so the customer does not get overcharged. I am trying to accomplish this by removing the submit-button class of the clicked div, so the next time the user clicks it, JQuery won't listen to the event that is associated with the submit-button preventing multiple submits.
Using the implementation below however, for some reason, does not prevent multiple submits, as intended.
HTML
<div class="submit-button button-style">Submit</div>
JQuery
$(".submit-button").click(function(){
$(this).removeClass("submit-button");
//**submit form**
});
NOTE: I must stick to a solution that uses the html above, so solutions using an input element of type submit, will not be useful.
I appreciate any suggestions on how to make this work. Many thanks in advance!
You can make use of .one() to prevent it from firing multiple times -
$(".submit-button").one('click',function(){
//**submit form**
});
http://api.jquery.com/one/
Edit :
In case of error :
function submitForm(){
//**submit form**
$.post('submit.php').error(function(){
// rebind event on error
$(".submit-button").one('click',submitForm);
});
}
$(".submit-button").one('click',submitForm);
You could use something like:
$('something').one('click', function(){
// submit code
});
Which will only fire once.
A significant portion of users don't bother clicking the submit button to submit a form - there's other more convenient ways, like hitting the enter key when the cursor focus is on a form field.
A more robust approach is to block the form via the forms submit event, and maintain a variable to keep track of the form submission state.
var submitted = false;
$("form#myForm").submit(function(evt){
if (submitted) {
evt.preventDefault();//stops form submission
return;
}
submitted = true;
});
I omitted form validation for this example.

Intercept form onSubmit

Is there any way we can intercept the html form's onsubmit event?
In my web application, there are several screens containing forms etc. The issue we are facing is when the user presses any button multiple times, the server gets overloaded with same requests.
Some of the forms have event handlers already attached to them(like onSubmit, button.onClick etc).
One way can be to "inject" my button disable code by going through all the screens.
But what I am looking for is a generic solution which can be applied to all the screens by just including the script where the function is written.
I know I can setup callback using jQuery (capturing onSubmit for form), but in the issue in this case is if any screen has a onSubmit registered already, it may not get called.
Any help in this regard appreciated!
I think this piece of code is a good place to start. It should be placed in separate file and included where you want to use it (if you appear to have global list of scripts - its a good place for it)
var suppressed_items = [];
function allowOnlyOne(item,e){
if (jQuery.inArray(item, suppressed_items)==-1){
//hi little item, I haven't saw you before, please go on... but I remember you
suppressed_items.push(item);
return true;
}
else{
//Hey, you have been submitted already, stay where you are!
return false; //or e.preventDefault(), it's a matter of faith :)
}
}
jQuery(document).ready(function(){
//don't worry, it won't replace your `ready` handlers, but just append new handler
jQuery("from").submit(function(e){
return allowOnlyOne(jQuery(this),e);
});
});
You can use the allowOnlyOne function with any item you wish. So, for example to allow single click on all hyperlinks, inside that ready handler add:
jQuery("a").click(e){
return allowOnlyOne(jQuery(this),e);
}
I hope you get the basic idea: catch the event, get the ID of the element that trigger it, fed it to AllowOnlyOne along with event.
Of course you can wrap it all around into self-executing closure to achieve incapsulation and so on...
If you already have jQuery I suggest you use it... All you need to do is make sure is that your form's onsubmit do not have a "return false" or else it can block jQuery's on submit.
Here's what you need to do:
Remove any return false from your form's onsubmit (if any). Don't worry we'll take care of this later in jQuery.
Add a class to your forms... something like "disableOnSubmit". Example:
<form action="something" onsubmit="yourExistingCode" class="disableOnClick">
</form>
OR
<form action="something" onsubmit="yourExistingCode" class="someOtherClass disableOnClick">
</form>
Implement a code similar to:
<script type="text/javascript">
$(document).ready(function(){
$('form.disableOnClick').submit(function(e){
// preventDefault() does the same as "return false;". It
// will not submit the form. If you're not using return false
// and want the form to be submitted remove the line below
e.preventDefault();
// Now diable any submit button
$('input[type=submit], button[type=submit]').attr('disabled, 'disabled');
});
});
</script>

Submit A Form Using Javascript

<form action="/?wpmlmethod=offsite&list=2&wpmlformid=" method="post">
...
</form>
I tried:
<script type="text/javascript">document.forms[0].submit();</script>
But it didn't work.
You should submit it on some click event, etc, for example:
elem = document.getElementById('button_id');
elem.onclick = function(){
document.forms[0].submit();
};
Update:
As you said form is already filled, you want to submit it straight away, you can try this instead:
window.onload = function(){
document.forms[0].submit();
};
Note that forms[0] represents the first form on your page, if there are more than one forms on your page, you will need to specify the correct index for it eg forms[1], forms[2], etc
Make sure you call the submit method after the form exists (either by placing the script after the form or using an onload or onready event)
Make sure you do not have a form control (e.g. an input) with the name or id of submit as this will clobber the submit method with a reference to that HTMLElementNode.
That said, you probably shouldn't be loading a page just to instantly submit a form with JS in the first place. You should have already had all the information needed on the server when you built the form. It smells of bad design and can break the back button.

Categories