I have a button outside of the form that when pressed, submits my form. That form has an event on it for onSubmit that fires off and then just does some form checks, making sure fields are present. At the end of the form, I return true and nothing happens. Can't seem to figure this out. Appreciate the extra set of eyes. I did verify that that function is being called and makes it all the way past the checks, just nothing happens. Here's the code:
$(document).on('click','.but_addTask',function(e){
e.preventDefault();
$('#addTaskForm').submit();
});
$(document).on('submit','#addTaskForm',function(e){
e.preventDefault();
var description = $('#description').val();
var dueDate = $('#dueDate').val();
if(!$('.taskClientID').length){
alert('Please add client(s) to task');
$('#taskClientSearch').focus();
return false;
}
if(description==""){
alert("Please enter a description")
$('#description').focus();
return false;
}
if(!$('.taskAuditorID').length){
alert('Please add owner(s) to task');
$('#taskOwnersSearch').focus();
return false;
}
if(dueDate==""){
alert("Please enter a dueDate")
$('#dueDate').focus();
return false;
}
console.log('made it!');
return true;
});
You already called e.preventDefault(); at the start of the callback, which suppresses the default behaviour of the event (in this case of course, that behaviour is to submit). By the time you return true it's too late.
If you remove that line, you should be ok.
Docs: https://api.jquery.com/event.preventdefault/
Related
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
I want to check if there's at least one checkbox that checked in a form after the submit button is clicked, if no, the the user should get message and the form SHOULDN'T be submit, so I wrote this code:
jQuery(document).ready(function ($) {
$('#price_quote_create_invoice').click(function () {
$('.price-quotes-table input[type="checkbox"]').each(function () {
if ( $(this).is(':checked') ){
$('#post').submit();
return false;
} else {
alert("You didn't chose any checkbox!");
return false;
}
}) ;
});
});
However, after I press ok on the alert box, the form does submit.
Any idea why this is happening?
Your code is almost right.
You return false on a click event but what you really want to do is to stop the submit event.
Change like this.
$('#yourFormId').submit(function(){
if (!$(this).find('input[type="checkbox"]:checked').length) {
alert("You didn't chose any checkbox!");
return false;
}
});
alert('You didn't chose any checkbox!');
You have an additional comma in your alert..
You can use event.preventDefault() to do this. event is the first argument of your click function. Reference
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;
}
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);
}
});
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.