jQuery Validate: validate form without throwing errors about empty fields - javascript

I have a field with about eight required fields. I have some code that only enables a button if all fields are validated. Then, I have a method that checks to see if all fields are valid - only then is the button enabled.
$("#FirstName").on("keyup blur", function () {
if ($("#FirstName").length > 0) {
if ($("#FirstName").valid()) {
isFirstNameValid = true;
}
else
isFirstNameValid = false;
checkIfAllFieldsAreValid();
}
})
The issue is that the required validation field is throwing an error when I tab to the next field, because the "keyup blur" event is firing on the next field even before I start typing. What event prevents this behavior from happening?

You can leave the submit button enabled and check when the user clicks it if the form is valid or not
$("#btnCreateMyAccount").on("click", function () {
if ($("#CreateAccountForm").valid()) {
return false;
}
else
{
//submit the data
}
})

Try checking if any of the inputs are empty before validating the form.
if($("your input field").val()=="") {
return;
}

Related

Stop a form from submitting

I have a form which is submitted using Ajax.
If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.
If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.
The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.
I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.
function check() is attached to the submit button.
Any and all advice is welcome.
If I can provide any additional information, let me know.
Thank you
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
As chandan suggested, I edited function check() and it works.
RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.
Anyway, this is the code that does the job:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
Function check() should work without any edits then.
Also, see code from this question

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

MVC - Issue with users double-clicking Submit button

I have a number of pages in my MVC app where the user clicks a Submit button to post a form. Sometimes users will click Submit and since nothing happens immediately, click it again. Therefore, the form submits twice. To prevent this, I have the following JavaScript code:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
This code disables the Submit button so the user cannot click twice. This works fine. However, if there are client side validation errors on the form, the Submit button gets disabled but the form is never posted, and now the user cannot post the form. Is there a change I can make to the JS code to detect if there were client side validation errors, and, if so, I either don't disable the Submit button, or reenable it?
If you are using jQuery Validate, you can check to see if the form is valid before disabling the button:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
You can try something like this:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
Switch it around.
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});

How do I trigger Form Submission in Javascript?

I have initialized my form submission like following:
$(document).ready(function() {
$("#my_form").submit(function(e) {
...
...
}
}
As you see above, it is in $(document).ready(...). When user press "Submit" button on UI, the form will be submitted.
But, How can I also trigger this form submission in Javascript besides user input (e.g. press submit button on UI)?
Call the submit() DOCs method on the form.
$("#my_form").submit();
You can use $("#my_form").submit();
$(document).ready(function () {
$("#SubmitForm").click(function (e) {
var textContent = $("#TextContent").val();
textContent = jQuery.trim(textContent);
if (textContent == "") {
alert("Content field cannot be empty.");
$("#TextContent").focus();
return false;
}
else{ $("#my_form").submit();
}
});
});

Difference in behaviour of function - JavaScript/jQuery

I've written some JavaScript/jQuery code that adds a users email to my newsletter database. There is a "subscribe" button to start the process, but I also wanted the user to be able to hit return for usability.
Weirdly, the code works for both the button and when the return key is hit in that the email is added to the database, but the callback function which just displays an alert is only triggered when the button is hit, not when the return key has been pressed.
$('#newsletter_button').click(function(event) {
newsletterSignup();
});
$('#newsletter_email').bind('keyup', function(event) { newsReturn(event); });
function newsletterSignup() {
var email = $.trim($('#newsletter_email').val());
if(!validateEmail(email)) {
alert('Please enter a valid email');
return false;
} else {
// add email to database
$.post('newsletterSignup.php',
{ email: email },
function(data) {alert(data);}
);
$('#newsletter_email').val("");
}
}
function newsReturn(evt) {
if (evt.keyCode == 13) {
newsletterSignup();
}
}
The function has to work the same no matter how it's been called surely! Like I say the post function is obviously being called both times because the email is being added to the database.
The only thing I can think of is that it's something to do with events. Not sure what though.
Browser behaviour for what happens when Enter is pressed is quirky. Whether the submit button is considered to be ‘clicked’ on Enter press varies between browsers and also depends on (a) the number of buttons in the form, and (b) the number of text inputs in the form. Typically when there is one text field and one button, the button won't be considered ‘successful’, you won't get a click event, and the button's name/value pair wouldn't be included in the submitted form values.
Additionally, trapping Enter keypresses in input fields is unreliable and shouldn't be done. This will fire in various circumstances when the Enter press shouldn't submit the form (eg when IMEs are in use), won't fire in places that should submit the form (eg some other element in the form has focus), and again there are browser differences.
So avoid all this pain: always bind to the submit event on the <form> containing the elements, instead of trying to second-guess what UI events should trigger that submission.
The first thing I can think of is evt.keyCode -- try using evt.which (a jQuery property which unifies the different browser behaviors).
Edit: Now I noticed the second alert. Your code is a tad messy, let's clean it up and see if the problem persists:
$('#newsletter_button').click(newsletterSignup);
$('#newsletter_email').keyup(newsReturn);
function newsletterSignup(e) {
e.preventDefault();
var email = $.trim($('#newsletter_email').val());
if (!validateEmail(email)) {
alert('Please enter a valid email');
} else {
// add email to database
$.post('newsletterSignup.php',
{ email: email },
function (data) { alert(data); }
);
$('#newsletter_email').val('');
}
return false;
}
function newsReturn(e) {
if (e.which === 13) {
newsletterSignup.apply(this, arguments);
}
}
Also, I don't know what your markup looks like, but if you were to use a form:
<form action="newsletterSignup.php" method="post" id="newsletter-form">
<input type="text" id="newsletter-email" name="newsletter_email"/>
<button type="submit">Go-go-gadget!</button>
</form>
Then you can skip the keyup stuff:
$('#newsletter-form').submit(newsletterSignup);
function newsletterSignup(e) {
e.preventDefault();
var email = $.trim($('#newsletter-email').val());
if (!validateEmail(email)) {
alert('Please enter a valid email');
return false;
} else {
// add email to database
$.post(this.action,
{ email: email },
function (data) { alert(data); }
);
$('#newsletter-email').val('');
}
return false;
}
Plus, people will be able to sign up even if you have a JavaScript problem on the page.

Categories