form not submitting issue - javascript

I have a code snippet like this.When I submit it shows alert button and ajax function calls.How can I prevent.I have a textbox with id=id1.I need to call ajax only if there is a value in textbox.
I have also another button in same page so I need to call common validate function inside that button also.So I wrote common function.
$( document ).ready(function() {
function validate() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function() {
validate();
$.ajax...code goes here
});
});

If it is not valid, return from the click handler without executing the ajax call.
In your case you are calling the validate method but you are not doing anything with the value returned from it. So use a if condition to check whether it is true or false, if false then return from the click handler
$(document).ready(function () {
function validate() {
if ($('#id1').val() == '') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function () {
if (!validate()) {
return;
}
$.ajax...code goes here
});
});

keep your functions out of jquery functions, to make it reusable across other places.
$( document ).ready(function() {
$('#button').click(function() {
var isValid = validate();
if(isValid){
$.ajax...code goes here
}
});
});
var validate = function() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
Return the validity of the check box and if it is true then trigger the ajax request.

Related

Event handler preventing submit

I have the very simple code below that installs an event handler on confirmPass keystrokes. On registration form submit I want to be able to disable the submit if the passwords do not match. In the 'onClick' event for the registration form if I call confirmPass() it fails to submit, if I comment it out it submits. Why is confirmPass() blocking the programatic form submit?
$( document ).ready(function() {
console.log( "ready!" );
$('#confirmPassword').keyup(function(){
confirmPass();
})
});
function registrationSubmit(){
confirmPass();
$('#registration').submit();
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (!(pass == cpass)) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
$('#registration').submit(function (event) {
event.preventDefault();
});
return;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!")
}
this line adds an event handler.
$('#registration').submit(function (event) {
event.preventDefault();
});
Which means every time the submit event is fired after this line have been hit it will be cancelled. Since you call confirmPass on each keystroke the line will be executed at least once and thus submits events on the form will always be cancelled. Instead you might want to only call submit only if the validations are succesfull and remove the line I mentionned above
Exemple
function registrationSubmit(event){
// Assuming you modify confirmPass to return true/false
if(confirmPass()){
$('#registration').submit();
}
}
You never remove the submit handlers that call preventDefault().
Instead of adding a handler in confirmPass(), check whether the password is valid in registrationSubmit(). Have confirmPass() return a boolean to indicate this.
$(document).ready(function() {
console.log("ready!");
$('#confirmPassword').keyup(function() {
confirmPass();
})
});
function registrationSubmit() {
if (confirmPass())
$('#registration').submit();
}
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (pass != cpass) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
return false;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!");
return true;
}
}

event.prevendefault() not working inside a function that has an each() function

I have function that will do a simple validation, if every input text is empyt an alert will pop up, and the program will stop. Function will fire up after a click of a button. I'm allready passing the event, but somehow the event.PreventDefault() not working, so still accessing the server side code.
Below is the function to do simple validation.
var checkRequired = function(event)
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
event.preventDefault();
}
}
});
}
For the trigger the function I use this code:
$(document).on('click','.box-load .btn-save', function(event) {
event.preventDefault();
checkRequired(event);
Bellow the checkRequired(), I'm gonna do an ajax request. What i want is, if one of the input text is empty, the event is stop. But with that code, is not working. Any suggestion?
Thanks in advance.
if you call event.preventDefault(), default action of the event will not be triggered.
$(document).on('click','.box-load .btn-save', function(event)
{
checkRequired(event);
event.preventDefault();
event.preventDefault() should be outside the for loop.
var checkRequired = function(event)
{
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
}
}
});
event.preventDefault();
}
event.preventDefault() will just stop the default action, not stop your function call. If you don't specifically return from your function, it will go on and launch the ajax.

Maximum call stack size exceeded with jQuery promise()

I'm trying to apply a simple form validation in jQuery. If a form field is empty, add a class error. If any of the fields are empty, don't submit. I have the following:
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$('#contact-form').submit();
}
});
});
Howerver when the code hits the line to submit the form, I am seeing a JavaScript error:
Uncaught RangeError: Maximum call stack size exceeded
Here's how your code would run if the form is valid:
on submit, prevent default action
check fields
if they are valid, form.submit - which causes submit event, goto step 1
endless recursion
it's very simple because there's no asynchronous code in the handler
$('#contact-form').submit(function(event) {
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
if (!formValid) {
event.preventDefault();
}
});
How many fields do you have to validate, and why promise associated to each of them? try after checking all fields
if(formValid) {
$('#contact-form').submit();
}
else return false
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$("#contact-form").off('submit').submit();
}
});
return false;
});
First, .promise().done(...) can be purged. As has been said, nothing asynchronous is going on.
That aside, the actual issue is most likely the repeated re-invocation of the submit handler.
Try a POJS (as opposed to jQuery) form submission :
if(formValid) {
this.submit();
}

jquery beforeunload messages depending on button clicked

Im having problem altering jQuerys beforeunload() functionality, depending on user actions.
$(document).ready(function() {
$(window).bind('beforeunload', function() {
if (billChanged == false) {
return false;
}
else if ( savebutton was clicked ) {
return false;
}
else {
return "refreshing page without saving, huh? you're a bad boy!";
}
});
});
The issue im having, that i can't come up with a way to check if 'savebutton' was clicked, as typed in else if clause in the snippet above.
The form itself is quite complicated, and i'm not able to alter it that much.
$(document).ready(function() {
var not_saved = true;
$('#saveButtonId').on('click', function() {
not_saved = false;
})
$(window).on('beforeunload', function() {
if (not_saved && billChanged)
return "refreshing page without saving, huh? you're a bad boy!";
}
});
});
you can define a global variable. Change it's value onclick of the button, and then check it in your function
var clickedButton = false;
Then your html
<input type="button" .... onclick="clickedButton=true;">
and then in your function
else if ( clickedButton ) {
return false;
}

Respect regular onsubmit handlers from jQuery.submit

I want a jQuery form submit handler to respect any previous submit handlers, including ones added with onsubmit.
I'm trying to detect the previous handler's return value but can't seem to do it:
<form><input type="submit" /></form>
<script type="text/javascript">
$('form')[0].onsubmit = function() { return false; }; // called first
$('form').submit(function(e) {
console.log(e.result); // undefined
console.log(e.isDefaultPrevented()); // false
console.log(e.isPropagationStopped()); // false
console.log(e.isImmediatePropagationStopped()); // false
});
</script>
Is there a way to do this?
I found one non-jQuery way to do this:
var form = $('form')[0];
var old_onsubmit = form.onsubmit;
form.onsubmit = function() {
if ($.isFunction(old_onsubmit)) {
if (old_onsubmit() === false) {
console.log("false");
return false;
}
}
console.log("true");
return true;
}
But I'd much prefer detecting this from the jQuery-bound submit handler

Categories

Resources