Solved

Dynamic JQuery Validation based on selected items on form

Posted on 2009-07-06
7
2,334 Views
Last Modified: 2012-06-27
I am using the jQuery inline form validation plugin below.  But I need to be able to dynamically change what fields are required based on various selections on a form.  

A basic example would be I have a dropdown and the person has to select their payment method.  How do I make the credit card fields validate if a credit card was selected as payment type but not if for example a field has a zero in it (i.e. no payment due) or if they selected check or invoice me from the drop down.



http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
0
Comment
Question by:polobruce
  • 4
  • 3
7 Comments
 
LVL 82

Expert Comment

by:hielo
ID: 24789732



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 

<html>

<head>

<title>Untitled</title>

<script language="JavaScript" type="text/javascript">

<!--

function validatePayment(payment)

{	//detect the payment type

	if( payment=="credit_card" )

	{

		// assign the relevant validation for each of the elements within the containing div

		$("#fullname").addClass("validate[required]");

		$("#cc").addClass("validate[required,onlyNumber]");

	}

	else if( payment=="cheque" )

	{

		//same logic as the "if" clause above

	}
 
 

	//now force the engine to rescan the page for elements that have "validate" in the class

      $("[class^=validate]").validationEngine({

      success :  false,

      failure : function() { callFailFunction()  }

      });
 

}

//-->

</script>
 

</head>

<body>

<select onchange="validatePayment">

	<option value="">make a selection</option>

	<option value="credit_card">Credit Card</option>

	<option value="cheque">Cheque</option>

</select>

<div id="credit_card">

	<input type="text" name="fullname" id="fullname" value="" />

	<input type="text" name="cc" id="cc" value="" />

</div>

</body>

</html>

Open in new window

0
 

Author Comment

by:polobruce
ID: 24794439
Thanks for the reply.  Ok so I had to make a few changes to the code you provided to get it to execute but i'm still having some issues.  I've attached my page so you can see what i've done.

So here's the issues.

I select credit card, don't fill any fields in and then hit submit.   The 3 fields that are required show correctly that they are required.

Then I select Check and hit submit.   It then shows correctly that only the 3rd field is required (this is a hard coded validation in that field).  

I then switch it back to credit card and hit submit and it still only thinks the 3rd field is required.

Now i'm not sure if this is correct, but in order to get the check validation to turn off the cc and fullname required validation I had to removeclass and then addclass with a validation optional flag.  For some reason if I didn't have that it wouldn't work and I would get a javascript error.  But with doing that it seems to work. .  Now, i've tried adding that same removeclass addclass type of code in the credit_card validation and it appears to require the fields, but only shows the bubble required text for the second and third fields.


Any ideas on how to resolve this?

Also, anyway that I can get the required field text removed if for example it was originally required and fields not filled out, but then when changing the value of the drop down they are no longer required.  Currently you have to tab into those fields to remove the required text.

Example: Select Credit Card, Submit, All fields show required.  Change dropdown to Check hit submit.  All fields still show required text.  Tab into first field and required text is removed.  Tab into second, text is removed.


Thanks!
I also would like to figure
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"><head>

		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

		<title>TopCon Registration</title>

		<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />

		<link rel="stylesheet" href="css/template.css" type="text/css" media="screen" title="no title" charset="utf-8" />

		

<script type='text/javascript' src='js/jquery.js'></script>
 

	

	

			

        

		<cfinclude template="/assets/javascripts/greybox/greybox.cfm">

        
 

    <!---

<script type="text/javascript">

document.getElementById("paymentinfo").style.display="block";

</script>

--->

    

	</head>
 

<body>
 

<script src='js/jquery.validationEngine.js' type='text/javascript'></script>
 
 

<script language="JavaScript" type="text/javascript">

<!--

function validatePayment(payment)

{       

//alert('starting the validation process');

var paymenttype = jQuery("#paymenttype").val();

//detect the payment type

        if( paymenttype=="credit_card" )

        {

			

                // assign the relevant validation for each of the elements within the containing div

				//jQuery("#fullname").removeClass();

				jQuery("#cc").addClass("validate[required]");

                jQuery("#fullname").addClass("validate[required]");

               

        }

        else if( paymenttype=="cheque" )

        {

		

				//alert('check please');
 

				jQuery("#fullname").removeClass();

                jQuery("#cc").removeClass();

                

				jQuery("#fullname").addClass("validate[optional]");

                jQuery("#cc").addClass("validate[optional]");

                //same logic as the "if" clause above

		        }

 

 

 

 

        

      jQuery("[class^=validate]").validationEngine({

      success :  false,

      failure : function() {}

      });

 

}

//-->

</script>
 

<form name="test" id="test" method="post">
 

<select name="paymenttype" id="paymenttype" onchange="validatePayment();">

        <option value="">make a selection</option>

        <option value="credit_card">Credit Card</option>

        <option value="cheque">Cheque</option>

</select>

<div id="credit_card">

        <input type="text" name="fullname" id="fullname" value="" />

        <input type="text" name="cc" id="cc" value="" />

</div>
 

<input type="text" name="bruce" id="bruce" class="validate[required]" value="" />
 

<input type="submit" name="submit" value="submit" />
 

</form>
 
 

</body>

</html>

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 24794522
I don't have that plugin installed, but I see you have:
 jQuery("#cc").removeClass();


If you dynamically added a class:
jQuery("#cc").addClass("validate[required]");


then, you should be removing only the class you added dynamically:
jQuery("#cc").removeClass("validate[required]");


NOT
jQuery("#cc").removeClass();
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:polobruce
ID: 24795716
Hielo,

I had tried removing just the class that I added, but then the issue becomes what class is the field currently set to.  i.e. is it blank.  is it validate optional or is it validate required.  

So I thought I would remove all classes for the field and reset them since specifying a class is an optional argument.

Thoughts?
0
 
LVL 82

Accepted Solution

by:
hielo earned 500 total points
ID: 24798102
in your plugin, look for this:
$("form").bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
 

		if(submitValidation(this) == false){
 
 

and replace it with this:

$("form").bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY

$(".formError").remove();

		if(submitValidation(this) == false){
 
 

Also, you need to call this:

 jQuery("[class^=validate]").validationEngine({

      success :  false,

      failure : function() {}

      });
 
 

again. Simply use:

<script language="JavaScript" type="text/javascript">

<!--

function validatePayment(payment)

{

	//alert('starting the validation process');

	var paymenttype = jQuery("#paymenttype").val();
 

	//detect the payment type

	if( paymenttype=="credit_card" )

	{

		$("#cc").addClass("validate[required]");

		$("#fullname").addClass("validate[required]");

	}

	else if( paymenttype=="cheque" )

	{

		$("#cc").removeClass("validate[required]");

		$("#fullname").removeClass("validate[required]");

	}
 

}

//-->

</script>

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 24798413
>>Also, you need to call this:
I meant to write:

"Also, you  NOT need to call this:"
0
 

Author Closing Comment

by:polobruce
ID: 31600337
THANK YOU SO MUCH!!!!! It working great now!

0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now