• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 918
  • Last Modified:

How to avoid clearing the value in textarea during validation in jquery?

I have a contact form with two input boxes for name and email address, and one textarea for message at the bottom. When I valid the value in each of these input, everything goes fine, except when you mess up with the any of those input boxes for name and email at the top, the value of textarea is also gone.

I don't want to clear the value of my textarea each time after something happens during the validation, any ideas?

Thanks.
0
jszeto
Asked:
jszeto
1 Solution
 
soupBoyCommented:
Can you post your code or link?  Are you using a validation plugin for jQuery?
0
 
COBOLdinosaurCommented:
If you are validating server side the way you should, then it is just a matter of modifying the validation script to retain the values on an error.  Of course that is just a guess, because you have not given us enough information to give you an answer.

Cd&
0
 
Kent DyerCommented:
In your form, are you doing a POST or GET?

HTH,

Kent
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
jszetoAuthor Commented:
This is the form:
<form action="mail/message.php" class="contactForm" name="cform" method="post">
	                <div class="input_boxes">
	                	<label for="name">Name  <span id="name-alert"></span></label><br />
	                    <input id="name" type="text" value="" name="name" maxlength="30" placeholder="Your Name"/><br />
	                    <label for="email">Email  <span id="email-alert"></span></label><br />
	                    <input id="email" type="text" value="" name="email" maxlength="30" placeholder="Your Email Address"/><br />
	                    <label for="message">Message  <span id="message-alert"></span></label><br />
	                    <textarea id="message" rows="5" cols="20" name="message" maxlength="400" placeholder="Your Message"></textarea>
	                 </div>   
	                 <input class="submit" type="submit" name="submit" value="Send" />
	                 <a href="" id="button"><span>Submit</span></a>
	        </form>

Open in new window


This is how I use jQuery for validation:
$(document).ready(function(){
	$('.contactForm').on('click', '.submit', function(e){
		e.preventDefault() //this prevents the form from submitting normally, but still allows the click to 'bubble up'.
		       
		//lets get our values from the form....
		var name = $('#name').val();
		var email = $('#email').val();
		var message = $('#message').val();

		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		//validation
		if ($('#name').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#name-alert').html('Do you mind telling me your name?');

			//disable the button
			return false;

		} else{$('#name-alert').html('');}


		//email input box
		if ($('#email').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#email-alert').html('It seems like you forgot your email.');

			//disable the button
			return false;

		} else if(!emailReg.test($('#email').val())){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();
			
			$('#email-alert').html('Ouch, is there a typo in your address?');

			return false;
		}

		else{$('#email-alert').html('');}


		//message textarea
		if ($('#message').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#message-alert').html('Share your thought with me.');

			//disable the button
			return false;
		} else{$('#message-alert').html('');}
		
		           
		//now lets make our ajax call
		$.ajax({
		  type: "POST",
		  url: "mail/message.php",
		  data: { name: name, email: email, message: message }}).done(function() {
		        
		//replace submit button with some text...
		$('#button').css('background-position', '0px -100px');
		$('#button span').html('Sent').css({'color':'#fff', 'left':'65px'});
		$('.submit').attr("disable", "true");
		$('.contactForm input').attr("value", "");
		$('.contactForm textarea').attr("value", "");
		           
		});       
	});
});

Open in new window

0
 
CWS (haripriya)Commented:
You ajax call is executed every time which clears your textarea.
Put that in 'else' part so that it does not execute.
0
 
Mohamed AbowardaSoftware EngineerCommented:
I have evaluated your code, the following works fine:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function(){
	$('.contactForm').on('click', '.submit', function(e){
		e.preventDefault() //this prevents the form from submitting normally, but still allows the click to 'bubble up'.
		       
		//lets get our values from the form....
		var name = $('#name').val();
		var email = $('#email').val();
		var message = $('#message').val();

		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		//validation
		if ($('#name').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#name-alert').html('Do you mind telling me your name?');

			//disable the button
			return false;

		} else{$('#name-alert').html('');}


		//email input box
		if ($('#email').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#email-alert').html('It seems like you forgot your email.');

			//disable the button
			return false;

		} else if(!emailReg.test($('#email').val())){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();
			
			$('#email-alert').html('Ouch, is there a typo in your address?');

			return false;
		}

		else{$('#email-alert').html('');}


		//message textarea
		if ($('#message').val()==""){
			$('#contact-wrapper').addClass('formshake');

			//to clone the contact-wrapper in order to reactivate the animation when submit button click
			var el = $('#contact-wrapper'),
			newone = el.clone(true);
			el.before(newone);
			$("." + el.attr("class") + ":last").remove();

			//add the alert message
			$('#message-alert').html('Share your thought with me.');

			//disable the button
			return false;
		} else{$('#message-alert').html('');}
		
		           
		//now lets make our ajax call
		$.ajax({
		  type: "POST",
		  url: "mail/message.php",
		  data: { name: name, email: email, message: message }}).done(function() {
		        
		//replace submit button with some text...
		$('#button').css('background-position', '0px -100px');
		$('#button span').html('Sent').css({'color':'#fff', 'left':'65px'});
		$('.submit').attr("disable", "true");
		$('.contactForm input').attr("value", "");
		$('.contactForm textarea').attr("value", "");
		           
		});       
	});
});
</script>
</head>
<body>
<form action="mail/message.php" class="contactForm" name="cform" method="post">
	                <div class="input_boxes">
	                	<label for="name">Name  <span id="name-alert"></span></label><br />
	                    <input id="name" type="text" value="" name="name" maxlength="30" placeholder="Your Name"/><br />
	                    <label for="email">Email  <span id="email-alert"></span></label><br />
	                    <input id="email" type="text" value="" name="email" maxlength="30" placeholder="Your Email Address"/><br />
	                    <label for="message">Message  <span id="message-alert"></span></label><br />
	                    <textarea id="message" rows="5" cols="20" name="message" maxlength="400" placeholder="Your Message"></textarea>
	                 </div>   
	                 <input class="submit" type="submit" name="submit" value="Send" />
	        </form>
</body>

Open in new window

0
 
nanharbisonCommented:
Using PHP, this is what I do, put I am not sure the textarea would be available as the $_POST element if you are using jquery, so you are not leaving the page.

echo '<textarea id="message" rows="5" cols="20" name="message" maxlength="400" placeholder="Your Message">'.$_POST['message'].'</textarea>';
0
 
jszetoAuthor Commented:
I used jQuery for validation and the form does not post to the server until it passes the validation. Wired thing is, this only happens to the textarea, the input textboxes for name and email are just fine. I am wondering whether it is because of the textarea type.
0
 
nanharbisonCommented:
The textarea field does very different things than textboxes. Is there some way to grab the contents of the message in jquery and if it exists, assign it to the textarea? I don't use jquery very much, so I don't know how to do this.
0
 
Ray PaseurCommented:
jQuery aside, your action= script will receive all of  the request inputs.  You have access to these in your PHP script.  If you must rewrite the form for the client to correct it, you can just rewrite the acceptable value= attributes back into the form.  This is applicable to every form input tag, including hidden and textarea.

<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

HTH, ~Ray
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now