Exiting from javascript function not working - javascript

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.

Related

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

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

Form submits on keyup after validation, instead of onclick

Here is a JSFiddle which will show the issue that I am having.
Currently, form data gets submitted on keyup as soon as that data is validated, which it should really only submit data when the 'subscribe' button is clicked.
So the form should work like this. If a user clicks the subscribe button, and a particular input fails validation, then that error should be shown. If the user then corrects the error, that specific error should clear on keyup, however, the user should have to click 'subscribe' before the form actually submits any data, or checks for validation again. Currently, the form submits on keyup after passing validation and that should not be the case.
I want to know how I can validate (not submit data) on keyup, as well as validate on click, in addition to submitting data on click.
http://jsfiddle.net/cqf8guys/5/
Code:
$(document).ready(function() {
$('form #response2').hide();
$('.txt1').on('keyup click', function(e) {
e.preventDefault();
var valid = '';
var required = ' is required';
var first = $('form #first').val();
var last = $('form #last').val();
var city = $('form #city').val();
var email = $('form #email').val();
var tempt = $('form #tempt').val();
var tempt2 = $('form #tempt2').val();
if(first=='' || first.length<=1) {
$('form #first').css('border','2px solid #ff0000');
$('form #first').css('background-color','#ffcece');
valid += '<p>Your first name is required</p>';
}
else {
$('form #first').removeAttr('style');
}
if(last=='' || last.length<=1) {
$('form #last').css('border','2px solid #ff0000');
$('form #last').css('background-color','#ffcece');
valid += '<p>Your last name' + required + '</p>';
}
else {
$(this).removeAttr('style');
}
if(city=='' || city.length<=1) {
$('form #city').css('border','2px solid #ff0000');
$('form #city').css('background-color','#ffcece');
valid += '<p>Please include your city</p>';
}
else {
$('form #city').removeAttr('style');
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>A valid E-Mail address is required</p>';
}
if (tempt != 'http://') {
valid += '<p>We can\'t allow spam bots.</p>';
}
if (tempt2 != '') {
valid += '<p>A human user' + required + '</p>';
}
if (valid != '') {
$('form #response2').removeClass().addClass('error2')
.html('' +valid).fadeIn('fast');
}
else {
$('form #response2').removeClass().addClass('processing2').html('<p style="top:0px; left:0px; text-align:center; line-height:1.5em;">Please wait while we process your information...</p>').fadeIn('fast');
var formData = $('form').serialize();
submitFormSubscribe(formData);
}
});
});
function submitFormSubscribe(formData) {
$.ajax({
type: 'POST',
url: 'http://3elementsreview.com/blog/wp-content/themes/3elements/php-signup/sign-up-complete.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 4000,
success: function(data) {
$('form #response2').removeClass().addClass((data.error === true) ? 'error2' : 'success2')
.html(data.msg).fadeIn('fast');
if ($('form #response2').hasClass('success2')) {
setTimeout("$('form #response2').fadeOut('fast')", 6000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('form #response2').removeClass().addClass('error2')
.html('<p>There was an <strong>' + errorThrown +
'</strong> error due to an <strong>' + textStatus +
'</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form')[0].reset();
}
});
};
This is because you have attached your functionality to the wrong event listener type. You don't want $('.txt1').on('keyup click', function(e) {... that's why it is getting mixed up when you deselect something. Instead you want the submit event listener like so....
$('.txt1').on('submit', function(e) {... or $('.txt1').submit(function(e) {...
then if the validation fails you can do an e.preventDefault(); and no form submission will occur.
Here is an example not using your own code...
JAVASCRIPT
var zipSwitch = false;
$(function() {
zipValidate();
validateForm(); //Add Form Submit Validation Event
});
//Constantly Monitor Validation
function zipValidate() {
$("#zip").keyup(function() {
var zipInput = $("#zip").val();
if($.isNumeric(zipInput)) {
$("#msgZone").html("Zip is correct");
$("#msgZone").attr("style", "border-color: rgb(4, 255, 17)");
zipSwitch = true;
} else {
$("#msgZone").html("Zip must be numbers only. Please remove letters.");
$("#msgZone").attr("style", "border-color: rgb(250, 20, 10)");
zipSwitch = false;
}
});
}
//Allow Form To Submit or Not Depending on Validation
function validateForm() {
$("#form1").submit(function(e) {
//If Form Validation Was Correct
if(zipSwitch==true) {
var validCountry = countryValidationFunction();
if(validCountry==true) {
alert("Form Submitted Successfully");
} else if(validCountry==false) {
alert("Please Enter a Valid Country");
e.preventDefault();
}
} else {
e.preventDefault();
}
});
}
HTML
<form name="form1" id="form1" action="#" method="POST" class="span12" style="margin-top: 50px;">
<div id="msgZone" class="well">
Validation Message Zone
</div>
<div class="controls-row">
<span class="help-inline control-list">Zip:</span>
<input id="zip" name="zip" type="text" class="input-medium" required="true" />
</div>
<hr />
<div class="controls-row">
<button type="submit" id="btnSubmit" class="btn btn-success" onSubmit="validateForm()">Submit</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
<hr />
</form>

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

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

Categories

Resources