jQuery submit 'this' form - javascript

I'm trying to submit a form, once the user has accepted they want to continue via the jQuery UI Dialog.
<form method="POST" action="url" onsubmit="return APP.dom.confirm(this);">
<button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
</form>
My APP.dom.confirm method looks like:
confirm: function(form) {
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(form).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
return false;
}
This works, however when they click confirm I'd like the form to get submitted.
$(form).submit();
That doesn't work. Logging it out I get the above HTML back. I've tried variations of, to no avail:
$(form).clostest('form').submit();
How do I submit this?

Change
$(form).submit();
to
form.submit();
When you call submit on a jQuery object, it calls your submit handler again. Calling it directly on the DOM element does not.
Example (interestingly, Stack Snippets won't let me submit a form, not even with target="_blank"):
var nesting = 0;
function submitHandler(form) {
var which = $(form).find("input[type=radio]:checked").val();
++nesting;
if (nesting > 5) {
snippet.log("Nested to 5, gave up");
} else {
if (which === "jQuery") {
snippet.log("Calling via jQuery, nesting = " + nesting);
$(form).submit();
} else {
snippet.log("Calling via DOM, nesting = " + nesting);
form.submit();
}
}
--nesting;
return false;
}
<form id="the-form"
onsubmit="return submitHandler(this);"
action="http://www.google.com/search"
target="_blank"
method="GET">
<input type="text" name="q" value="kittens">
<div>
<label>
<input type="radio" name="opts" value="jQuery"> Submit with jQuery
</label>
</div>
<div>
<label>
<input type="radio" name="opts" value="DOM"> Submit with DOM
</label>
</div>
<button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

confirm: function() {
var that = this;
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(that).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
}
Replace onsubmit="return APP.dom.confirm(this);" by
$('form').on('submit', APP.dom.confirm);

Related

jquery submit form and stay on same page not working

The code below is supposed to submit the form and stay on the current page. It does submit the form, but it doesn't stay on the same page as it redirects to the form processing page. I have tried using event.preventDefault(); and return false; but neither are stopping the redirect. I tried them one at a time and then later added both at the same time and at different locations in the function, but the redirect still happens.
function submitForm() {
var $subForm = $('#signupForm')[0] ;
if (!$subForm.checkValidity()) {
$subForm.find(':submit').click() ;
return ;
}
$subForm.submit(function(event){
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
return false ; // not working here
}
My form is defined as:
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
....
<button type="button" onclick='submitForm();' id="ccInfoButton" style="" class="btn btn-primary buttonSignup" disabled >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
The issue is because of where you are trying to handle the submit event. The code below achieves the goal of submitting the form and staying on the same page. You can see it work with the code snippet below.
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
<!DOCTYPE html>
<html>
<body>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
</script>
</html>
#DankyiAnnoKwaku - kudos to Dankyi for getting me on the right track, but his solution didn't work for me, I had to adapt it a bit more:
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
// Had to wrap the `submit(function(event)` in the root `$(document).ready ....`
$(document).ready(function(event) {
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
}) ;
</script>

Trigger action attribute of form from javascript function

I have validated all my form fields and after that, I would like to trigger form action from submit function. I have tried many ways but nothing seems to work. Any help appreciated.
(function() {
//FORM VALIDATOR
formValidator = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
//MAIN PARENT ELEMENT
this.contactForm = document.getElementById("contactForm");
//MAIN FORM ELEMENTS
this.formBody = document.getElementById("formBody");
this.inputContainer = document.getElementsByClassName("inputContainer");
//USER INPUT ELEMENTS
//INPUT FIELDS
this.fields = {
company: document.getElementById("company"),
industry: document.getElementById("industry"),
//rest of the fields
};
this.submitBtn = document.getElementById("submit");
}
submitForm: function() {
//I want to trigger form action from this part but nothing seems to work
document.getElementById("myForm").action = "https://google.com";
}
};
//INITIATE FORM VALIDATOR
formValidator.init();
}());
//HTML
<div id="formBody" class="formBody">
<form action="https://google.com" method="POST" name="becomessaform" id="becomessaform">
<input type=hidden name="oid" value="****">
<input type=hidden name="retURL" value="">
<div class="row form-fields ">
{/* all fields go here */}
</div>
<div class="row form-fields submit-button-cf"><input type="submit" id="submit" name="submit" class="button-submit"/></div>
</form>
</div>
You can submit a form in JS by using submit().
In your code, that would be:
submitForm: function() {
document.getElementById("becomessaform").submit();
};

Html form submit after ajax

Trying to make some database validation with Jquery Get method before submitting a form. But I get the error
Uncaught TypeError: form.submit is not a function
Got the logic form here
Simplified Code below (but the err is still there...)
<html>
<body>
<div id="insertCertificateForm">
<form action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = this;
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
}
else {
return false;
}
});
});</script>
</body>
</html>
Because after clicking button this would mean the current button and
insertCertificateForm was never a form anyways...it was Div
best would be to bind the form with an ID #myForm
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="insertCertificateForm">
<form id="Myform" action="/Certificates/Insert" method="post">
<div>
<label>Charge</label>
<input name="Charge" id="Charge" />
</div>
<input type="submit" value="Insert" class="btn btn-default" />
</form>
</div>
<script>
$('#insertCertificateForm').submit(function (e) {
e.preventDefault();
var form = $("#Myform");
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
form.submit();
} else {
return false;
}
});
});
</script>
</body>
</html>
and also load your scripts in the head
Your selector is wrong $('#insertCertificateForm'), if you want to do like this you need to add this id into your form <form id="insertCertificateForm" otherwise follow this way,
$('form').submit(function (e) {
e.preventDefault();
var Charge = $('#Charge').val();
$.get("/Certificates/CheckIfChargeIsUnique", { Charge: Charge }, function (data) {
if (data) {
$(this).submit();
} else {
return false;
}
});
});
That's because you're calling this and not $(this) when declaring the form variable. You can either declare it as $(this) or use $(form) to submit the form.

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

JQuery validate disable button until all fields are active, but it should not show error on every key press

Here is my Fiddle
Here is the html
<form action='includes/pgd_cc.php' METHOD='POST' id="ccSelectForm">
<div class="control-group">
<label class="control-label" for="inputEmail"><strong>Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmail" placeholder="jane.smith#email.com" id="inputEmail" />
</div>
<label class="control-label" for="inputEmailConfirm"><strong>Confirm Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmailConfirm" placeholder="jane.smith#email.com" id="inputEmailConfirm" />
</div>
</div>
<button type="submit" id="emailSubmit" disabled="disabled" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Click me to buy">Credit Card Checkout ยป</button>
Here is the script
$(document).ready(function () {
$('#ccSelectForm').validate({
rules: {
inputEmail: {
required: true,
email: true
},
inputEmailConfirm: {
equalTo: '#inputEmail'
}
}
});
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
});
As i am doing
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
My Form is always getting validated and showing errors.
I don't want to show the errors in the form while the user type a single word itself.
I want to show errors only after going to next field and it should only validate the current field is typed.
How can i alter this code to achieve this..
It is better to bind it to the submit. So that, it validates everything only once, and not every time for every input, when the keyup is fired. Try this:
$('#emailSubmit').on('click', function () {
return $('#ccSelectForm').valid();
});
Fiddle: http://output.jsbin.com/valiwetese

Categories

Resources