$("#form").submit(); is not working as expected - javascript

I have two buttons(save, publish) defined in my form. If i Click 'save' and then 'publish' , publish button is not working. The issue here is, save function works fine as expected. But when clicking 'publish', what happens is it tries to submit the form and rather to validate the form which defines under 'publish' function, it goes to 'save' function's validate function and further process.I would like to know why it skips that and jump to 'save' function's validate process?
The sample code;
Form:
<form class="form-horizontal" method="POST" id="manage_form">
<div class="form-actions" id="saveButtons">
<button class="btn btn-primary" id="save"/>save</button>
<% if (outputs.isPermitted) { %>
<a class="btn btn-info" id="publish">Publish</a>
<% } %>
</div>
</form>
Jquery
// cache var to eliminate unnecessary re-querying
var $manageForm = $('#manage_form');
$('#save').click(function (e) {
var v = $("#manage_form").validate({
submitHandler: function(form) {
if(!validate_tiers()){
return false;
}
var designer = APIDesigner();
$('#swagger').val(JSON.stringify(designer.api_doc));
$('#saveMessage').show();
$('#saveButtons').hide();
$(form).ajaxSubmit({
success:function(responseText, statusText, xhr, $form) {
//............
});
$("#manage_form").submit();
});
$('#publish').click(function(e){
alert('xxx');
e.preventDefault();
var v = $("#manage_form").validate({
submitHandler: function(form) {
if(!validate_tiers()){
return false;
}
var designer = APIDesigner();
$('#swagger').val(JSON.stringify(designer.api_doc));
$('#saveMessage').show();
$('#saveButtons').hide();
$(form).ajaxSubmit({
success:function(responseText, statusText, xhr, $form) {
$('#saveMessage').hide();
$('#saveButtons').show();
if (!responseText.error) {
$( "body" ).trigger( "api_saved" );
} else {
if (responseText.message == "timeout") {
if (ssoEnabled) {
var currentLoc = window.location.pathname;
if (currentLoc.indexOf(".jag") >= 0) {
location.href = "index.jag";
} else {
location.href = 'site/pages/index.jag';
}
} else {
jagg.showLogin();
}
} else {
jagg.message({content:responseText.message,type:"error"});
}
}
}, dataType: 'json'
});
}
});
alert('zzz');
$manageForm.submit();
});

Prevent default submitting of form simply use:
e.preventDefault();
Use different submit handler for each button, This is what you want:
$('#myform').validate({
});
$('#submit').click(function(e) {
e.preventDefault();
$("#myform").data("validator").settings.submitHandler = function (form) {
alert('submit with submit');
//your code
return false;
};
$('#myform').submit();
return false;
});
$('#publish').click(function(e) {
e.preventDefault();
$("#myform").data("validator").settings.submitHandler = function (form) {
alert('submit with publish');
//your code
return false;
};
$('#myform').submit();
return false;
});
DEMO

prevent the default form behavior of submit.
edit: wouldn't you want your submit in the submit handlers?
$(function() {
// cache var to eliminate unnecessary re-querying
var $manageForm = $('#manage_form');
$('#save').click(function (e) {
e.preventDefault();
var v = $manageForm.validate({
submitHandler: function (form) {
$manageForm.submit();
}
});
});
$('#publish').click(function (e) {
e.preventDefault();
var v = $manageForm.validate({
submitHandler: function (form) {
alert('yyy');
$manageForm.submit();
}
});
});
});

Related

Validating individual form inputs with javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});
You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO
This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Message about sent is not working

I have code that checks whether the address is ok and sends it. After sending the information appears that the message was sent.
When I give the wrong email address format - appears the message.
Then when I give the correct address - the message you sent is not working.
What is wrong?
jQuery code:
<script type="text/javascript">
{literal}
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
{/literal}
$(document).ready(function() {
$('#mybtn').click(function() {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
//e.preventDefault();
}
if (validateEmail(sEmail)) {
$('#contact').submit(function() {
$.ajax({
url : '/contact/process',
data : $('#contact').serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
return false;
});
}
else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
</script>
<script type="text/javascript">
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
$(document).ready(function() {
$('#contact').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : '/contact/process',
data : $(this).serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
});
$('#mybtn').on('click', function(e) {
e.preventDefault();
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
}
if (validateEmail(sEmail)) {
$('#contact').trigger('submit');
} else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
Try this way, first set listener on your contact form, second listen for event on "send button"
If it's "simple form" you could just put everything in on('submit') listener
Fiddle

Exiting from javascript function not working

I have this javascript function:
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
}
What am hoping this achieves is, if the input field is empty, display the alert and remain in the function.If it isn't then continue.
My submit button is linked to another page but this page is displayed anyways regardless of what happens in the if statement.
This is the form code:
<form id="post" action="http://localhost:8080/uploadNewMessage" method="post">
<fieldset>
<div data-role="fieldcontain">
<label for="msg" class="input">Message:</label>
<input type="text" name="msg" id="msg" size="10"/>
</div>
Submit
</fieldset>
</form>
and the full javascript code just incase:
$(document).ready(function() {
// 1. The Registration button
$("#submit").bind('click', function(event) {
displayMessage();
});
});
function doPostRequest(postData) {
$.ajax({
type: "POST",
url: URL,
dataType: "json",
data: postData
});
}
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
doPostRequest(postData);
}
You may try something like this:
$("#submit").bind('click', function(event) {
var message = $.trim($("#msg").val());
if(!message.length) {
alert("You need to enter a message");
return false;
}
else {
event.preventDefault();
doPostRequest({"message":message});
}
});
demo
$(function() {
$("#submit").on('click', function(event) {
event.preventDefault(); // prevent default anchor behavior
displayMessage();
});
});
and also:
function displayMessage() {
var message = $.trim( $("#msg").val() ); // trim whitespaces
if (message === "") {
alert("You need to enter a message");
}else{ // Use the else statement
doPostRequest({
"message" : message
});
}
}
The event variable that is passed via your click event handler contains a function named preventDefault. If you don't want the form to submit, call this (event.preventDefault()). This will prevent the submit button from submitting the form.

Jquery Form on submit show success message

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});
submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}
There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

Prevent AJAX form from submitting twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur?
HTML
<form class="submit-form" method="post">
<input type="url" class="content-link" name="content_link" placeholder="Link" />
<input type="email" class="email" name="email" placeholder="Your Email Address" />
<button class="submit-modal-button submit-button"><span>Send<span class="ss-icon">send</span></span></button>
<p class="terms">By clicking Submit you agree to our Terms & Conditions</p>
</form>
JavaScript
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]'),
viewport_size = $(window).width() + "x" + $(window).height(),
user_browser = BrowserDetect.browser,
user_os = BrowserDetect.OS,
current_page = document.location.href;
$('.submit-form input[type="url"],.submit-form input[type="email"]').blur(function () {
if ($.trim($(this).val()) == '') {
$(this).addClass('form-validation-error');
return false;
} else {
$(this).removeClass('form-validation-error');
}
});
form.submit(function () {
if ($.trim(content_link.val()) == '' && $.trim(email.val()) == '') {
content_link.addClass('form-validation-error');
email.addClass('form-validation-error');
return false;
}
else if ($.trim(content_link.val()) == '') {
content_link.addClass('form-validation-error');
return false;
}
else if ($.trim(email.val()) == '') {
email.addClass('form-validation-error');
return false;
} else {
var env = TTB.getEnvironment();
$('.submit-modal-button').attr('disabled','disabled');
$(document).ajaxStart(function () {
$('.submit-modal .screen-1').delay(300).append('<span class="loading2"></span>');
});
$.ajax({
url: env.submit_modal_process,
type: 'POST',
data: {
    content_link: content_link.val(),
    email: email.val(),
viewportsize: viewport_size,
browser: user_browser,
os: user_os,
current_page: current_page
  },
success: function () {
$('.submit-modal .screen-1').delay(1000).fadeOut(300, function () {
$('.submit-modal .screen-1').fadeOut(500, function () {
$('span.loading2').detach();
$('.submit-modal .screen-2').fadeIn(500, function () {
$('.submit-modal .screen-2').append('<img class="carlton" src=' + env.the_environment + TTB.config.image_path() + 'submit-modal-success.gif' + ' />');
});
$('.submit-modal .screen-2').css('display','block').delay(4200).fadeOut(500, function () {
$('.carlton').hide();
$('.submit-modal .screen-1').fadeIn(500);
content_link.val('');
email.val('');
content_link.focus();
email.removeClass('form-validation-error');
$('.submit-modal-button').removeAttr('disabled');
});
});
});
}
});
return false;
}
});
}
EXAMPLE.processSubmitModal();
If to remove all non relevant to the issue code from your snippets we will get the following:
HTML
<form class="submit-form" method="post">
<input type="url" name="content_link" />
<input type="email" name="email" />
<button>Send</button>
</form>
JavaScript
$(function() {
var EXAMPLE = {
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]');
form.submit(function () {
$.ajax({
url: document.location.href,
type: 'POST',
data: {
content_link: content_link.val(),
email: email.val()
},
success: function () { // <-- The function that is executed twice
// Do something
}
});
return false;
});
}
};
EXAMPLE.processSubmitModal();
// And somewhere in the code that was not presented in snippet...
EXAMPLE.processSubmitModal();
});
I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.
Try like this
form.submit(function (event) {
if(event.handled !== true)
{
//put your ajax code
event.handled = true;
}
return false;
});
Refernce

Categories

Resources