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();
};
Related
I have a login form that has a validator with javascript, I am using Google invisible Recaptcha either.
when I don't use Recaptcha the form is working completely correct but when I am using Recaptcha it calls a javascript function to submit the form and I cannot use validator inside that function.
I do not have much knowledge about javascript so any help would be appreciated.
HTML Code:
<form class="form-horizontal form-material validate-form" id="loginform" method="post" action="" role="form">
<h3 class="box-title m-b-20">Login</h3>
<div class="Input-Style">
<div class="wrap-input2 validate-input" data-validate="Email is uvalid">
<input class="input2" id="inputEmail" type="text" name="username" autofocus>
<span class="focus-input2" data-placeholder="your email"></span>
</div>
</div>
<div class="Input-Style">
<div class="wrap-input2 validate-input" data-validate="password is required">
<input class="input2" id="inputPassword" type="password" name="password">
<span class="focus-input2" data-placeholder="your password"></span>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button id="login" class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light g-recaptcha"
data-sitekey="" data-callback="enableSubmit">Login
</button>
</div>
</div>
</form>
Javascript Code:
(function ($) {
"use strict";
/*==================================================================
[ Validate ]*/
var username = $('.validate-input input[name="username"]');
var password = $('.validate-input input[name="password"]');
$('.validate-form').on('submit',function(){
var check = true;
if($(username).val().trim().match(/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
showValidate(username);
check=false;
}
if($(password).val().trim() == ''){
showValidate(password);
check=false;
}
return check;
});
$('.validate-form .input2').each(function(){
$(this).focus(function(){
hideValidate(this);
});
});
function showValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).addClass('alert-validate');
}
function hideValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).removeClass('alert-validate');
}
})(jQuery);
Modify the first lines of your JavaScript:
[...]
/*==================================================================
[ Validate ]*/
var username = $('.validate-input input[name="username"]');
var password = $('.validate-input input[name="password"]');
var verifyCallback = function(){
var check = true;
[...]
So, the validation function is not bound to the submit event (which is caught by Recaptcha) but to a variable.
Additionally, at these lines after the validateCallback function:
[...]
return check;
});
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback': verifyCallback
});
[...]
Now, first the captcha will be checked and afterwards your validation will be performed as a so called "callback" method.
You need to use grecaptcha.render callback. You also need to create separate functions which will validate your form like this:
function formValidator() {
// validation script will be here
}
and pass this function to grecaptcha.render method
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : formValidator,
'theme' : 'dark'
});
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.
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]);
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);
I have two partial screens. One or the other can be open at the same time.
A login form:
<form action="/Account/Login" id="login-form" class="form" method="post">
<button id="login" type="submit">Login</button>
<button id="register" type="button" onclick="location.href='/Account/Register'">Register</button>
</form>
and a registration form:
<form action="/Account/Register" class="form" id="register-form" method="post">
<button id="register" type="submit">Register</button>
<button id="login" type="button" onclick="location.href='/Account/Login'">Login</button>
</form>
In the layout screen there is common logic for putting a message on the screen:
<p id="authentication-progress"></p>
<script type="text/javascript">
(function() {
document.getElementsByClassName('form')[0]
.addEventListener("submit", function () {
document.getElementById("login").disabled = true;
document.getElementById("register").disabled = true;
document.getElementById('authentication-progress').innerHTML = 'System: Authenticating '
setInterval(function () {
document.getElementById('authentication-progress').innerHTML += '. ';
}, 3000);
// document.getElementById("loading-mask").style.display = "block";
}, false);
})();
</script>
Is there some way that I change it so the message is different for login and registration.
On login: System: Authenticating
On registration: System: Registering
Yes - by checking what is the id of the element the given event is the target, as:
.addEventListener("submit", function (ev) {
document.getElementById('authentication-progress').innerHTML = ev.target.getAttribute('id') == "register-form" ? "System: Registering" : "System: Authenticating";
});
JSFiddle: http://jsfiddle.net/njqP7/