Preventing submission after jQuery Validation Engine - javascript

Once clicking button, wanting to prevent submission to local storage if any required fields are not filled out. Both functions work properly. Just trying to prevent LocalStorage.save() from hitting if $("#formID").validationEngine(); finds a required field not completed.
<form id="formID" name="myForm">
<input class="validate[required]" type="text" id="agree" name="agree"/>
<button type="submit" value="Save" id="Save" onclick="clicked();">Submit Survey</button>
</form>
<script type="text/javascript">
function clicked() {
if (confirm('Are you sure you want to submit?')) {
$("#formID").validationEngine();
my.LocalStorage.save();
} else {
return false;
}
}
</script>

From their documentation at http://posabsolute.github.io/jQuery-Validation-Engine/:
validate
Validates a form or field, displays error prompts accordingly.
Returns true if the form validates, false if it contains errors.
It is inversed for fields, it return false on validate and true on errors.
When using form validation with ajax, it returns undefined, the
result is delivered asynchronously via function options.onAjaxFormComplete.
// form validation
alert( $("#formID1").validationEngine('validate') );
// field validation
alert( $("#emailInput").validationEngine('validate') );
So that would change your code to:
function clicked (e)
{
if ( confirm('Are you sure you want to submit?') )
if ( $("#formID").validationEngine('validate') )
my.LocalStorage.save();
e.preventDefault();
}
Take note that I added e as a parameter that needs event passed in via:
<button type="submit" value="Save" id="Save" onclick="clicked(event);">
Submit Survey
</button>

From source code there is a function validate() which returns true/false after validating
so use it
if( $("#formID1").validationEngine('validate'))
{
my.LocalStorage.save();
}
check this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

Related

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

jQuery validate is not working when the button is outside the form

I have a problem where jQuery validate is not working when the submit button is placed outside the form tags (which is required form my Cordova mobile app). As soon as .validate is called, the execution stops.
My HTML is set-up this way:
<form id="form-cart" >
// All form fields here
</form>
<ons-bottom-toolbar>
<button class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
And the function is then called as:
function addToBasket()
{
$.validate({
form : '#form-cart',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
// Run ajax on success
}
};
sNavigator.pushPage("confirmation.html", options);
return false;
}
});
}
How can I get this working so that it validates and calls ajax even if the button is outside of the form tags?
According to jQuery validation plugin documentation there are two different methods:
validate() – Validates the selected form.
valid() – Checks whether the selected form or selected elements are valid.
So you should set up the form validation with .validate method outside your function and check if form is valid inside your function (see code example below):
$('#form-cart').validate({
});
function addToBasket() {
if ($('#form-cart).valid())
//do you onSuccess stuff
}
}
Try this :
<form id="form-cart" >
// All form fields here
// Don't give <input type="submit"> here
</form>
<ons-bottom-toolbar>
<button type="submit" id="submitBtn" class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
and
$(document).ready(function () {
$("#submitBtn").click(function () {
$("#form-cart").submit();
});
});

Form not submiting on chrome but in firefox submitting

I have a submmit button like Following:
Save & Continue
And My function in js is:
function checkCreditDebit(buttonValues) {
//Some validation here
//Disable Button if once clicked to prevent twice form submission
document.getElementById('saveandcontinue').disabled = 'disabled';
document.getElementById('onlysave').disabled = 'disabled';
}
But when i submit form in firefox it disabled the "save & continue", button and submit form. But in chrome it disable the button but not submit the form. What is the wrong with this please suggest. Thanks in Advance
Instead of just disabling your submit button(forms can also be submitted if you press enter on text-boxes), attach a handler to your form that will leave a 'class name' to your form as a mark that the form was already submitted, if the user submit the form again, the handler should check if the form has already the class name, then prevent duplicate submission via event.preventDefault().
try this:
<form onsubmit="prevent_duplicate(event,this);" action="">
<input type="text" />
<input type="submit" />
</form>
<script>
function prevent_duplicate(event,form)
{
if((" "+form.className+" ").indexOf(" submitted ") > -1)
{
alert("can't submit more than once!!!");
event.preventDefault();
}
else
{
form.classList.add("submitted");
}
}
</script>
Demo here
instead of disabling pervent multiple submit by setting a javascript flag example :
<form method="post" id="ecomFormBean" name="ecomFormBean" onsubmit="return checkSubmit(this);" >
<input type="text" />
<input type="submit" />
</form>
<script>
var formSubmitted = false;
function checkSubmit(f){
if (formSubmitted) {
alert('Please be patient. Your order may take 10 - 15 seconds to process. Thank you!');
return false;
}
else return formSubmitted = true;
}
</script>
Chrome runs javascript very fast. So it might be possible your checkCreditDebit(buttonValues) function which is to disable submit button executes before your php script submits the form.
I suggest you to call setTimeOut function before calling the javascript function so that the form can get submitted.
Give it a try.

Preventing form submission after validation by parsley.js

I have used parsley.js many times and have literally copied the code from my last use of parsley.
However, every time I submit the form the page refreshes. preventDefault seems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?
<script>
$(function(){
$("#register_signup").submit(function(e){
e.preventDefault();
var form = $(this);
if ($('#rform').parsley( 'isValid' )){
alert('valid');
}
});
});
</script>
<form id='rform' name='rform' data-parsley-validate>
<input id='reg_password' class='register_input' type='text' autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>
You are binding the submit event to a input element. If you check the jquery $.submit() documentation, it states that:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
This is your main problem and this is why alert will never be displayed (in fact, that code is never executed).
I would also change a few things:
$('#rform').parsley( 'validate' ) should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
$('#rform').parsley( 'isValid' ) should be $('#rform').parsley().isValid().
Use $.on() instead of $.submit().
Remove onClickfrom the register_signup element. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
So, your code will be something like this:
<form id='rform' name='rform'>
<input id='reg_password' class='register_input' type='text' autocomplete="off"
data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" value='Sign Up' />
</form>
<script>
$(document).ready(function() {
$("#rform").on('submit', function(e){
e.preventDefault();
var form = $(this);
form.parsley().validate();
if (form.parsley().isValid()){
alert('valid');
}
});
});
</script>
if you are using parsely 2 you can try this
$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
//whenValid return promise if success enter then function if failed enter catch
var ok = formInstance.whenValid()
//on success validation
.then(function(){
alert('v');
formInstance.reset();
})
//on failure validation
.catch(function(){
formInstance.destroy();
});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
// console.log(formInstance);
if (!ok)
formInstance.validationResult = false;
console.log(formInstance);
});
//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});
//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
alert('dd');
});
});
for more details parsely documentation check Form with examples and events
When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run.
But if you applying javascript return false when parsely() not valid.
And just make sure you have include parsley.js code file.

Stop form submission with submit eventlistener

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.
Am I making some stupid mistake?
<form id="highlight">
Row: <input type="text" name="rows" value="1" id="rows">
Column: <input type="text" name="cells" value="1" id="cells">
<input type="submit" name="Submit" value="Highlight" id="Submit">
</form>
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
alert('hi');
return false;
}, false);
</script>
I always call event.preventDefault() on event listeners that I want to cancel the event for, as well as return false. This always works for me.
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function(event)
{
event.preventDefault();
alert('hi');
return false;
}, false);
</script>
To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Once submitted, the validateForm() method can prevent submission if necessary:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Well this is the way I would do it :
function validate (form)
{
// return false if some fields are not right
}
function setup_form_validation (form)
{
form.addEventListener (
'submit',
function (f) { // closure to pass the form to event handler
return function (evt) {
if (!validate (f)) evt.preventDefault();
// Return status doesn't work consistently across browsers,
// and since the default submit event will not be called in case
// of validation failure, what we return does not matter anyway.
// Better return true or nothing in case you want to chain other
// handlers to the submit event (why you would want do that is
// another question)
};
} (form),
false);
}
I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.
And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

Categories

Resources