Validate on button click using validationEngine bootstrap - javascript

I was doing this. and i was doing pretty ok with the tutorial i am doing the validation for form like this
<script>
jQuery(document).ready(function() {
jQuery("#formID2").validationEngine('attach', {
onValidationComplete: function(form, status) {
alert("The form status is: " + status + ", it will never submit");
}
})
});
</script>
I am wondering how to make the validation using button click.. I want to remove the submit form and i want to put the validation on button click. Any suggestion is appreciated

$("#Button1").click(function () {
var valid = $("#form1").validationEngine('validate');
var vars = $("#form1").serialize();
if (valid == true) {
alert("Hi");
} else {
$("#form1").validationEngine();
}
});
Try this one i got it from here it worked for me!

When Button type is == Submit then use follwing code,
$("#FormId").validationEngine({
onValidationComplete : function(form, status) {
if (status) {
alert("Hi");
}
return false;
},
scroll : false,
});

Related

My website refreshes everytime I run my code

$(document).ready(function() {
$("#btn").click(function() {
$("#form").toggle();
});
$("#submit").click(function() {
if ($(".product").checked = true) {
alert("Thank You!")
} else {
alert('Please Choose A Product');
}
var name = $("input:text").val();
var nLi = $("<li>").appendTo("ul");
nLi.text(name);
});
});
Everytime I put text in the text input, the <li> will display for only a moment, but the page will refresh and it will disappear. Sorry if this is obvious, I'm still learning.
Don't allow the page to refresh. Return false at the end.
$(document).ready(function() {
$("#btn").click(function() {
$("#form").toggle();
});
$("#submit").click(function() {
if ($(".product").checked) {
alert("Thank You!")
} else {
alert('Please Choose A Product');
}
var name = $("input:text").val();
var nLi = $("<li>").appendTo("ul");
nLi.text(name);
return false;
});
});
And please change
if ($(".product").checked = true) {
to
if ($(".product").checked == true) {
Try to use event.preventDefault() in your click event, for example:
$("#submit").click(function(e) {
e.preventDefault();
}
for more info about this jquery method event.preventDefault()

jQuery Stop submitting form by checking error variable

I have a simple form with some form fields. Some of them are required some are not. The required field are required by adding the class 'required'.
When I submit I check the #contact-form fields and on the basis of there I give the empty field error classes and submit the form yes or no.
Adding the error classes to the fields is not a problem, but checking the "error" variable is. Because I don't know where I can check the error variable.
This is my jQuery code:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
JsFiddle
The following code should do what you want, just give your contact form submit button the id of #contact-form-button.
$('#contact-form-button').click(function(e) { // using click function
// on contact form submit button
e.preventDefault(); // stop form from submitting right away
var error = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
error = true;
}
});
if (!error) { // if not any errors
$('#contact-form').submit(); // you submit form
}
});
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
return false;
}
return true;
})
if validation cross successfully then it return true for submit the form
I found out that my code just works. The reason I thought it was not working, is because I was still using PHP handling my real website where I made 1 field required and in my jQuery not. This made the confusion.
So the following code works:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});

jQuery: event.preventdefault();

If I create the click events and their handler on my own, it is no problem for me to execute event.preventdefault() at the right place. But if there is an element, which already has registered click events and corresponding handler, I want to deactivate its further working (e.g. submitting) in a certain case.
This is the example:
There is a submit button on the page, with registered click elements (maybe about hundred validation routines.. ) and a variable (al) with a certain value. Be the instantaneous value of this variable = 5 (it is not the desired certain case -> with value = 3).
HTML
// other form elements
<input type="submit" name="next" value="go"/>
JavaScript with jQuery
var al = 3;
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
In this example I cannot prevent the form is being submitted. What is my mistake?
EDIT: event.preventDefault ist not the problem, sublime (my editor) corrects it anyway.
----- I WANT TO SIMPLIFY THE QUESTION ---------
That is a SubmitButon (this time from yii in the original context):
VIEW
echo CHtml::submitButton(
Yii::t ('Somethin', 'next'),
array(
'name' => 'next',
'onclick' => "checkDetails()"
));
JS
checkDetails() {
PREVENT_SUBMITTING
}
How should PREVENT_SUBMITTING look? What would prevent submitting in this case, without any condition?
change
event.preventdefault();
to
event.preventDefault();
you have to write the "D" as capital letter.
You can do this two ways
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
or
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
return false;
} else {
alert ('OK');
return true;
}
}
);
Now I have a working solution:
VIEW
echo PHtml::submitButton(Yii::t('Something', 'next'),
array(
'name' => 'next',
'onclick' => "return checkDetails(event)",
)
);
jQuery
function checkDetails (event) {
event.preventDefault();
event.returnValue =false; // for IE
return false;
}
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
Try this Change event.preventDefault();
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
I recently needed to use .off() instead of .preventDefault(). I needed to intercept and block one event handler while still allowing the main click event to bubble up. Might be what you need.
Besides from this problem I ll suggestion you to separate the validation part e. g
Add another form input e.g proceed
<input type="hidden" name="proceed" value="0"/>
<input type="submit" name="next" value="go"/>
Add custom validation method
jQuery.validator.addMethod("validateSteps", function(value, element) {
return value == 3 ? false : true;
}, "*");
Add validation rule to you form
$("#your_form_id").validate({
rules: {
"proceed": {
validateSteps: true
}
},
messages: {
"proceed": {
validateSteps: "custom message"
}
}
});
You have to set proper value to proceed input field before. This way you do not need to wade through event issues. And its more customizable e.g if you have ten steps with different validation requirements on each step

I want to detect if a user types a certain string into a textbox

I have a textbox that looks like this
<%= Html.TextBoxFor(model => model.ContactAddress, new { autocomplete = "off", maxlength = "75" })%>
in my javascript i have this
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("HEY NO P.O. BOXES ALLOWED ");
}
document.forms[0].submit();
});
i was hoping that this would pop up the alert before posting if the user had 'box' in the textbox. it doesnt work though.
I want to show an alert if the user enters the string 'box' in their address (the textbox).
EDIT: on the submit i am going to use a confirm box to verify that the user wants to continue. thanks for the help
Using
$("#textboxid").blur(function(){
if( $("#textboxid").val() == "box"){
alert("box typed!");
}
});
this will make your life easy!
Try this -
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("blah");
}else {
alert('Bleh');
}
alert("TEST");
$('form').eq(0).submit();
});
You can do this:
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if (addr1.indexOf("box") > -1) alert("blah");
else alert('Bleh');
$('#formID').submit();
});
Instead of:
if(~addr1.indexOf("box")) {...} else {...}
Try
if(addr1 === "box") {...} else {...}
You could use regex to test the string for the occurrence of "box". This will allow you to do a case-insensitive search:
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var input = $('#test').val();
if (/box/i.test(input)) {
alert("bad");
} else {
alert("good");
$("form").submit();
}
});
You should also put the "submit" function in your "else" statement so the form only submits on validation success.
NOTE: this could cause unwanted issues if the user happens to live on "box street".

Form won't submit once error checking breaks it

I'm working on a project where I have some error checking. However, the form wanted to submit each time so I had to break the submit. Here is what I did.
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "order-form" }))
{
...
<input type="submit" name="btnSaveOpv#(item.Id)" value="#T("Admin.Common.Save")" id="btnSaveOpv#(item.Id)" class="adminButton" style="display: none;" onclick="SaveBtn(#item.Id);" />
...
var originalIssuedQty = 0;
function SaveBtn(id) {
var quantity = parseInt($("#pvQuantity" + id).val());
var issuedQty = parseInt($("#pvIssuedQty" + id).val());
var stockQty = parseInt($("#hfStockQty" + id).val());
var availableStockQty = stockQty + parseInt(originalIssuedQty);
//Issued Quantity cannot exceed Quantity (you can't issue more than requested)
if (issuedQty > quantity) {
alert("Issued Quantity cannot exceed Quantity.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Make sure Issued Quantity is within Available Stock Quantity
if (issuedQty > availableStockQty) {
alert("There is not enough Products in Stock to issue this amount.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Present confirmation
var result = confirm('#T("Admin.Common.AreYouSure")');
if (!result) {
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
else {
$("#order-form").submit(function (e) { this.submit(); });
//$("#order-form").submit(function (e) { return true; });
}
}
...
}
Here is the problem. Whenever I try to submit the first time without triggering any of my error checking, things work. When I trigger the error checking, things work. However, if I fix the error and try to submit again, the page merely refreshes. Any ideas on this would be very helpful. Thanks.
You are making things too complicated.
This is a basic template on how you do validation and how you stop the form from submitting when it's not valid:
$(function() {
$("#order-form").submit(function (e) {
var isValid = false;
// Do your validation here and put the result in the variable isValid
if ( !isValid ) {
e.preventDefault(); // If the form is invalid stop the submit, otherwise proceed
}
});
});
Every time you call $("#order-form").submit(function (e) { whatever });, you add an additional handler function. It doesn't remove the handlers you've already added. This is probably why it breaks.
Repeatedly changing the submit event handler is a messy way to do it. Instead, you should have a single function which handles the submit event, and that function should do (or call) the error checking, and preventDefault() if necessary (like ZippyV is suggesting).

Categories

Resources