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();
}
});
});
Related
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 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
}
}
});
Currently I have several text inputs and then a type image submit button. On the submit button I have onmouseover, onmouseout, etc.. This sends those to a javascript function that handles change of images for a hover effect. What I wanna do is submit the form and then do some checking like do passwords match and such. Would I do something with the action attribute of the form tag to submit it to a javascript function?
Firstly I recommend using something like jQuery. It makes the code a lot easier to manage. Here's how you'd do it in jQuery:
$('form').submit(function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
Here's how you'd do it in pure javascript:
// function to make sure we add the event correctly no matter which browser
function addEvent(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
}
// get first form on page
var form = document.forms[0];
addEvent('submit', form, function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
<form onsubmit="return cancel()"><input type="submit" /></form>
<script>
function cancel()
{
//code validation
var validated = false;
if(!validated)return false;
else return true;
}
</script>