Stop a form from submitting - javascript

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

Related

jQuery Validate: validate form without throwing errors about empty fields

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;
}

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);
}
});

Make text appear when submit button clicked and checkbox is unchecked

I am trying to create an agree to terms and agreements. However, when the button is unchecked and the user hits submit, I want it to present the user with an alert telling him to agree to the terms. At first, I made it to where the user couldn't even click on the submit button when the checkbox is unchecked, however, I want the user to be able to click it so he can be alerted with an error. I can't seem to get my code to work no matter what.
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
if(document.getElementById('submit').click() & document.getElementById("myCheck").checked = false;){
alert("Hello! I am an alert box!!");
}
}
<input type="checkbox" id="checkme"/>
I agree to the terms & service<br />
<input type="submit" name="sendNewSms" class="md-trigger blue-texture postbit-button-big md-pointer" data-modal="modal-five" id="submit" value=" Send " onclick="$('.md-modal').removeClass('md-show');" disabled/>
I want the user to be able to click it so he can be alerted with an error
Remove the disabled from the submit button.
Remove the checker.onchange = function(){
Make sure to event.preventDefault(); browser triggering form submits or other default evett actions
All you need:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
sendbtn.onclick = function( event ){
event.preventDefault();
if(!checker.checked){
alert("You must agree to our terms of service");
}
};
Note that you might want to do the above not on button Click but on formID.onsubmit (the form can always be submitted even without a Button click. Not seeing your form this is all I can suggest.)
P.S:
Developer Console (access by F12 and click Console) helps to debug such errors like &/&& =/=== missing ; etc...
P.S2: when using only JS a handy function to fast-get an element by ID can be achieved with a nice little function i.e:
function ID(id){return document.getElementById(id);} // ...and use like:
var submitBtn = ID("submit");
document.getElementById("myCheck").checked = false; is assigning it to false. If you want to check if it is false, you need this
document.getElementById("myCheck").checked === false;
Remove disabled from submit and the other js and use this:
$('#submit').click(function(e) {
if (!$('#checkme').is(':checked')) {
e.preventDefault();
alert('Check the box!');
} else {
$(e.currentTarget).parent('form').first().submit();
}
});

jQuery Validate stop form submit

I am using jQuery validate to the form, but when the form is validated it reloads or submits the page I want to stop that action. I already use the event.preventDefault(), but it doesn't work.
Here is my code:
$("#step1form").validate();
$("#step1form").on("submit", function(e){
var isValid = $("#step1form").valid();
if(isValid){
e.preventDefault();
// Things i would like to do after validation
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
$(".third_step_form").fadeIn();
$(".third_inactive").fadeOut();
}else if(counter < 3){
$(".second_step_form").fadeIn();
$(".third_inactive").fadeIn();
}
$(".first_step_summary").fadeIn();
$(".second_inactive").fadeOut();
}
return false;
});
The submitHandler is a callback function built into the plugin.
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid. Gets
the form as the only argument. Replaces the default submit. The right
place to submit a form via Ajax after it validated.
Since the submitHandler automatically captures the click of the submit button and only fires on a valid form, you do not need another submit handler, nor do you need to use valid() to test the form.
You code can be replaced with:
$("#step1form").validate({
submitHandler: function(form) {
// Things I would like to do after validation
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
$(".third_step_form").fadeIn();
$(".third_inactive").fadeOut();
}else if(counter < 3){
$(".second_step_form").fadeIn();
$(".third_inactive").fadeIn();
}
$(".first_step_summary").fadeIn();
$(".second_inactive").fadeOut();
return false; // block the default submit action
}
});
I use this basic structure for all my JS validation, which does what your asking
$('#form').on('submit', function() {
// check validation
if (some_value != "valid") {
return false;
}
});
You don't need e.preventDefault(); and a return false; statement, they do the same thing.
The plugin provides callbacks for valid and invalid form submission attempts. If you provide a submitHandler callback then the form doesn't get submitted to the server automatically.
$("#step1form").validate({
submitHandler : function()
{
// the form is valid
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
// etc
}
}
});

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();
}
});
});

Categories