Javascript/Jquery, callback before submit that changes attribute values - javascript

I have a several forms my webpage, they can be in any location or order...
<form id="carform" action='/form.php' js-url='http:www.domain.com/formA.php' >
...
</form>
<form id="truckform" action='/form.php' js-url='http:www.domain.com/formB.php' >
...
</form>
<form id="boatform" action='/form.php' js-url='http:www.domain.com/formC.php' >
...
</form>
I would like to add a callback that can replace the action attribute value with the js-url value. I am not sure how to reference the relevant form values. Any help appreciated.
This would be easier if I was referencing a specific form id, but in this case, the code needs to reference the submitting form, whichever it is.
document.addEventListener("DOMContentLoaded", function(event) {
$('form').submit(function() {
// Change the action attribute to the js-url attribute value if js-url attribute
return true; // submit the form
});
});
Doing this is plain Javascript is ok too.

Related

How add name input submit() jQuery

I have a JavaScript that changes the attribute of the input button to "disabled", so the user don't submit the page twice.
// Disables multiple submit
function disableSubmit (btn, submitForm) {
// Sets button as disabled, changes class and cursor
$(btn).attr("disabled", true);
$(btn).toggleClass("disabled alt2");
$(btn).css('cursor', 'initial');
$(btn).attr("value", "Sender...");
// Submits form
$(submitForm).submit();
}
// Disables submit for order form
$("#send-order").click(function () {
return disableSubmit(this, "#order");
});
The problem is that I need to track the name of the button submitting the page so I can handle it in my Django view.py file.
HTML
<input value="Send bestilling" id="foo" name="send-order" type="submit" class="button alt2">
View.py
request.POST.get("send-order", False)
But if I use my script to submit the page, I can't get the name of the input submitting the page. Is there any way to set a name for the button submitting the page in my script?
I tried this but didn't work:
$(submitForm).submit().attr("name", "send-order");
Solution
I had to change the code inside views.py in order to make this work.
you can use preventdefault or return false
$("#send-order").click(function (event) {
event.preventDefault();
return disableSubmit(this, "#order");
});
Or
<input id="send-order" value="Send" type="submit" onclick="disableSubmit(this, '#order');return false" />
One way you can do this is by creating a hidden input on your form, with a name of its own. Something like below.
<input type="hidden" name="buttonName" id="buttonName" />
Then, in your disableSubmit function, make it set the value of that input before submitting.
$(submitForm)
.find("input[name=buttonName]")
.attr("value",
$(btn).attr("name")
);
From there, you can just retrieve the "buttonName" value in your View.py.

stop form submitting in a function - jquery / javascript

The codes posted might be not consistent because I am continuing someone's work and trying not to make too much changes if possible.
Anyways, there's this form which has inputs for others to input values.
upon submitting, if the input field is empty an alert will pop up and should stop the form from submitting.
I have tried using both return false; and event.preventDefault(); inside the if input field is empty but the form still submits.
trying to cut this short because the script is hell lots
just a simple form
<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="addDesc();">
<button type="submit" class="add-to-cart" alt='Add this product to your shopping cart now.'>Add to Cart <span class="fa fa-cart-plus"></span></button>
</form>
the function
function addDesc(desc){
// some variables to be passed when form submits
// an $.each function to loop through something
//inside the loop it'll push input values into an array called checkEmpty
if(jQuery.inArray("", checkEmpty) !== -1){
alert('Please Do not leave any input fields empty.');
return false;
}else{
//some outputs
}
}
return false is the first I tried but form still submitted.
I even tried something like
$('.add-to-cart').on('click', addDesc(event));
and inside addDesc() instead of return false I used event.preventDefault()
Thanks in advance.
Very simple. Just add a return before calling the function onsubmit:
<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="return addDesc();">
Should do the trick (returning true or false will send the form or prevent the submission).
Take a look at Working example.
HTML :
<form action="cart.php" method="post" name="ordering" id="ordering">
<button type="submit" class="add-to-cart" alt='Add this product to your shopping cart now.'>Add to Cart <span class="fa fa-cart-plus"></span></button>
</form>
JS :
$( "#ordering" ).submit(function( event ) {
if(jQuery.inArray('', checkEmpty) !== -1){
alert('Please Do not leave any input fields empty.');
event.preventDefault();
}else{
alert('submiting');
}
});
You're using JQuery so you don't have to use inline onsubmit.
Hope this helps.
You are executing addDesc at the time of binding it, so the return value of that function is used.
Try this
$('.add-to-cart').on('click', addDesc);
or
onsubmit="addDesc"
change the button type as 'button" instead of 'submit'.And then you can call the function in the event of the button click.

Unable to submit form using Javascript

I am trying to submit my form named 'vform' by using javascript and ajax.Here
Button named 'show' is being used to show the 'div' containing form named vform and that form calls codevalidate function and there it submits the form using some ajax code..Where i am getting error is vform.submit().Here's the html and js code(I know error is in if condition but do not know where)
html:
<button id="show" onClick="javascript:codefield(); return false";>Apply for Discount</button>
<div id="apply" style="display:none">Voucher code<br>
<form id="vform" name="vform" action="" method="post" onsubmit="javascript:codevalidate(); return false;" >
<input type="text" name="code" id="code"><br>
<span id="error" style="color:red"></span><br>
<input type="submit" name="btn" value="apply" id="btn" ></form>
</div>
javascript:
function codevalidate()
{
if(document.getElementById('code').value!=="")
{
$.post("couponajax.php",{code:$("#code").val()},
function(data)
{
if(data=='1')
{
//alert("success");
vform.submit();
return true;
}
else
{
document.getElementById('error').innerHTML="You have entered a wrong code!";
return false;
}
});
}
else
{
document.getElementById('error').innerHTML="Code can't be empty!";
return false;
}
return false;
}
codefield function is just displaying the div on onclick event and ajax call is just checking whether the code exists in database or not..if exists returns 1 else 0.
The problem is alert message is being displayed but form is not being submitted. How can I fix this problem?
I think you are missing jquery selector.
Try to replace
vform.submit();
with
$("#vform").submit();
or you can call submit button click event like
$("#btn").click();
You are not selecting the form.
Try changing;
vform.submit();
To:
$("#vform").submit();
Please try this one, works for me.
document.getElementById("vform").submit();
Try this
document.forms["vform"].submit();
Hope this helps.
You don't have to submit form with code.
Just call validation function and control submit flow with preventDefault function.
var codevalidate = function(e) {
if (!validationCode) { // if validation code didn't pass
e.preventDefault(); // prevent form from submitting
}
}
// register callback that will be called when user submits form
document.getElementById("vform").addEventListener('onsubmit', codevalidate);
That way form will be submitted by user only if validation pass.
Also check if your data is actually returning '1' by calling console.log(data);
Form will be submitted to the current address if action is empty, is that ok?
The thing is that:
action attribute of your form element is empty. So it is being submitted but to the same page from which it is calling the .submit() method.
so you should specify action attribute first of all like:
<form id="vform" name="vform" action="vfrom_submit.php" method="post"
onsubmit="javascript:codevalidate(); return false;" >
.....
</form>
Also try changing
vform.submit();
to:
$("#vform").submit();
//OR
// document.getElementById("vform").submit();
// Although vform.submit() can also work.
Hope it helps, cheers :)!
You should use:
document.getElementById("vform").submit();
Update:
Try removing "return false;" from onsubmit attribute and remove "vform.submit();" from the if condition as well.

jQuery form action change

Normally to change the action attribute of a form in jQuery I would do the following:
<form id="removeLightboxForm" action="">
...
</form>
$('#removeLightboxForm').attr("action", "view/#close");
But I usually use this for when the action attribute is empty on the HTML form tag itself. I'm now trying to use this on a form where the action attribute already contains a default URL and is causing problems.
In this example, the form action is present:
<form id="removeLightboxForm" action="view/">
...
</form>
But when I do this:
$('#removeLightboxForm').attr("action", "view/#close");
I end up with the new URL/action being added to the original URL/action, for example:
<form action="view/view/#close" ...
Is this how it's supposed to work or am I doing something wrong?
I would try clearing it first:
$('#removeLightboxForm').attr("action", "").attr("action", "view/#close");
or
$('#removeLightboxForm').removeAttr("action").attr("action", "view/#close");

jQuery - submit multiple forms through single request, without Ajax

I have a page with several forms.
I am trying to submit one of the forms (say form A) (NOT through Ajax, since I need to load the result page after the submit is processed), BUT I need another form's contents (say form B) to be submitted TOGETHER with form A, i.e. the contents of forms A + B should be submitted TOGETHER to the SAME URL, as one request, and as I said before, NOT as an Ajax request.
The submit should be by a POST request. Also, the forms contain ONLY fields that are not file upload (i.e. input, select, textarea fields).
I have seen suggestions here such as
Posting/submitting multiple forms in jQuery
or
Submitting two forms with a single button
but pay attention that these do not match my case, since the forms are submitted in different requests, and/or they are submitted through Ajax.
I was thinking of getting the contents of one of the forms by (the jQuery's) serialize(), but how do I attach that string to a form submitted by POST?
Or maybe you have other ideas how to accomplish this?
SOLUTION:
Based on the ideas of Sheepy, I wrote the following code. I am also using the answer by Pointy from the following link:
submit multiple forms to same page
//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
var forms = [];
$.each($.makeArray(arguments), function(index, value) {
forms[index] = document.forms[value];
});
var targetForm = forms[0];
$.each(forms, function(i, f) {
if (i != 0) {
$(f).find('input, select, textarea')
.hide()
.appendTo($(targetForm));
}
});
$(targetForm).submit();
}
Well, you have to copy the data from form2 to form1 before the submit. Here is the basic to get you started:
$.each ( $('#form2 input, #form2 select, #form2 textarea').serializeArray(), function ( i, obj ) {
$('<input type="hidden">').prop( obj ).appendTo( $('#form1') );
} );
This function would select inputs from form2, get their current values, then create a new hidden input for each of them and add them to form1.
Depending on your scenario you may want to check the existance of input with same name on form1 first.
A solution to inject the data directly in the post request (and not in a sub field)
<form id="form1">
<input ... />
<input ... />
</form>
<form id="form2">
<input ... />
<input ... />
</form>
<form id="result" action="..." method="POST" onsubmit="merge(); return true;">
<input type="submit" />
</form>
<script type="text/javascript">
function merge() {
$result = $("#result");
$("#form1 input, #form2 input, #form1 select, #form2 select, #form1 textarea, #form2 textarea").each(function() {
$result.append("<input type='hidden' name='"+$(this).attr('name')+"' value='"+$(this).val()+"' />");
});
}
</script>
You can only do one request at a time and that will reload the page unless you use AJAX. The only other option would be to create a script which concatantes the seralizations of your two forms - but at that point, why wouldn't you just use one large form..
Edit: For your combining the two forms, there is an example of this in the answer of the second link you provided.
form A:
<form method="post" action="next.html" onsubmit="this.formbVal.value = $('#formb').serialize(); return true;">
<input type="hidden" name="formbVal" value="" />
<input type="submit">
</form>
form B:
<form id="formb" method="post" action="#" onsubmit="return false;">
</form>
I discovered that your solution will copy the form to another invissible form, but the backside is that the original forms will be cleared an such edit of the original form (eg after form validation errors) is not possible.
To solve this i tried to clone the elements before appending it to the invissible form. I edited your code like this:
//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
var forms = [];
$.each($.makeArray(arguments), function(index, value) {
forms[index] = document.forms[value];
});
var targetForm = forms[0];
$.each(forms, function(i, f) {
if (i != 0) {
$(f).find('input, select, textarea')
.clone()
.hide()
.appendTo($(targetForm));
}
});
Unfortunatly now it doesn't copy the selected values in a select element.
Hope someone can help me to impove this script
you can do some thing like this
$('#SubmitBtn).click(function () {
$("#formId").attr("action", "http://www.YourSite.com/");
$("#formId").attr("method", "post");
$("#formId").attr("target","_blank");
$('#formId').submit();
});
this will submit the for to http://www.YourSite.com/ in a new window

Categories

Resources