page gets refreshed on submit click - javascript

i have multiple validation on my form.. when i enter wrong data and click on submit button its shows the error message for a second and page gets refreshed..This is only few functions.there are other functions also.. Individually, they work fine. but when i try to run all , it doesnt work.
javascript:
function req()
{
if (document.reg_indi_form.txt_fnm.value=="")
{
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
document.getElementById('i').style.fontSize="12px";
}
if (document.reg_indi_form.txt_lnm.value=="")
{
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
document.getElementById('i1').style.fontSize="12px";
}
return false;
}
function validateUname() {
submitFlag = true;
var len=document.reg_indi_form.txt_usrnm.value.length;
if(len<6){
submitFlag=false;
document.getElementById('i2').innerHTML="*enter atleast 6 char";
document.getElementById('i2').style.color="red";
}
return submitFlag;
}
function alls()
{
req();
validateUname();
}
html:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data">
There is also php code in my file.

Change your function alls() to:
function alls()
{
return req() && validateUname(); // Your function must return false otherwise it will be considered as true
}
Whenever you are binding event & want to stop propagation, just return false ( which you are doing ) but your function alls() was not returning anything which will not stop event propagation further.

Your functions alls() has no return statement and therefore returns an undefined. The only return value that prevents the default action is false. Any other return value, including undefined, allows the default action to take place.
change your function alls() to look like this:
function alls() {
req();
return validateUname();
}

In function alls()
function alls()
{
return req() && validateUname(); // Equivalent to-- if(req() && validateUname()) {return true;} else{ return false;}
}

Related

How to Prevent Bubbling For Form Submit

I have form that calls the function GenerateWords when it is submitted and returns false.
<form id="3Form" onsubmit="GenerateWords(this); return false;">
This is causing problems with Google Tag Manager implementation as it does not bubble up to the form submit listener.
I understand event.preventDefault(); needs to be used and return false removed but don't know how to implement this. The current javascript I have is:
function GenerateWords(F) {
var strWords = F.words.value;
if ... condition is false
return false;
}
if ... condition is false
return false;
}
vars declared
for (var i = 0; i < ctLines; i++) {
var strLine = arrLines[i];
strLine = Trim(strLine.replace(/[\r]/g,""));
if successful condition
}
}
F.result.value = oResult.join("");
F.result.focus();
}
Any help would be appreciated. Thanks.
Try this in javascript:
function GenerateWords(F,ev) { // event object
...
if(someCondition) // condition when the form should not be submitted.
ev.preventDefault();
}
and you may remove return false; from the form tag and pass the event reference
<form id="3Form" onsubmit="GenerateWords(this,event);">

Check if input field is empty on fields with jQuery

I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.

jQuery - trying to do a function inside an if statement

I'm trying to add some validation to a form. I have a jQuery function that is doing exactly what I want:
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
However, I want to change it so that this function only runs if a radio button elsewhere on the page is selected. So I tried this:
if (jQuery('#top').checked) {
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
}
That doesn't work - the function doesn't get called even if #top is checked. Can anyone explain why? I'm used to PHP, and JavaScript often throws curveballs at me.
What does firebug or Chrome console tell you? You could try something like this:
$('#top').is(':checked')
as in (thanks RET):
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
}
return false;
});
try
$('#top').is(':checked')
but the function submit only binds the function and calls it every time submit is clicked.
so you must put the checked check in the submit function
jQuery('#post').submit(function() {
if(!$('top').is(':checked')){ return };
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
});
Yeah, that logic won't quite do what you're hoping for. Try something like:
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
// all your existing code
I could be wrong, but I don't think the answer given by #greener is going to work, because that will only declare the submit function if #top is checked at page create time.

Stop redirect in JavaScript

I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit

Form validation does not happen

My form has some fields that are mandatory and I have marked them with class="required". I am writing the below jquery to validate this form, but it doesn't happen. I think either I am messing with calling the two functions or I am not getting the proper element through $(this).
<script type="text/javascript">
function validatemyForm() {
$('.required').each(function() {
if($(this).val() == "" || $(this).replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Filed</span>');
return false;
}
else {
$(this).remove();
}
})
return true;
}
</script>
I am calling the form, from the onsubmit event handler <form id="myform" onsubmit ="return validatemyForm();">. Am I incorrectly using each and this of jQuery?
A number of things:
You can use replace on a String, whilst you use it on a jQuery object. There is no $(this).replace. If you want to check for whitespace, you need the value, i.e. $(this).val().replace.
You use $(this).insertAfter which means that the input element is inserted after the span. $(this).remove simply removes the input element which isn't what you're after either I think.
You return false in the each(), but this doesn't return that value in the validatemyForm function. In that function, you always return true.
I changed it to this to get it working: http://jsfiddle.net/DaDQT/6/.
Your function validatemyForm always returns true. The return false you have in there is inside the function passed to each. validatemyFormdoes not stop at this point.
The following should work as you expect it (untested code):
<script type="text/javascript">
function validatemyForm() {
var ok = true;
$('.required').each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Field</span>');
ok = false;
}
else {
$(this).remove();
}
})
return ok;
}
</script>

Categories

Resources