Link to home
Start Free TrialLog in
Avatar of atljarman
atljarman

asked on

JQuery Form Validation Conditional Textarea Required based on Select Box

Hi,

I have a form with multiple select boxes and comment boxes.  In the example below, I only include one of each for simplicity.  The ids of each correspond with the Question number.  For example, question 2 would be Q2Answer (select) and Q2Comments for the text area.

I am curently using jquery.validate.js to validate the form.  Its a pretty cool plug in but I need to validate the text area in two reasons: 1) if the text area is over a specific character count (250 - resolved), and 2) if the user choose "N/A" or "No" from the corresponding select box, then the user needs to be required to enter a commment (why they selected that value).  

This is the code that i have that works to validate making the select box required, making the textarea required, and making it so that only 250 chars can be entered.  What I need to do is only make the textarea required if the select value is "N/A" or "No."

<script>
$().ready(function() {
   // validate the comment form when it is submitted
    $('textarea').autosize();
    $('#FORM006' ).validate({
             rules: { Q1Comments: { required: true, maxlength: 250 }
                      ,Q1Answer: { required: true }
} 
             , messages: { Q1Comments: { required: 'Enter a comment', maxlength: jQuery.format('Enter at most {0} characters') }}
     });
});
</script>
</head>
<body>

<form id='FORM006' method='POST' action=''>

<p>
<select id='Q1Answer' name='Q1Answer' title='Please select a response' alt='Q1 Answer' class='dropdownfield' required>
	<option value=''>Please Select</option>
	<option value='Yes'>Yes</option>
	<option value='No'>No</option>
	<option value='N/A'>N/A</option>
   </select>
</p>
<p>   <textarea id='Q1Comments' name='Q1Comments' alt='Q1Comments' title='Enter any comments' class='textarea expand'></textarea></p>

<p><input class='submit' type='submit' value='Submit'/></p>

</form>

Open in new window


Most points goes to answers with modified scripts.  I've been working on this for a few hours and i'm starting to not be able to focus on the screen any more.
Avatar of atljarman
atljarman

ASKER

I think something like this is needed:

// f = the form you're validating
if(FORM006.Q1Answer.options[FORM006.Q1Answer.selectedIndex].value=="N/A"){
// validate Q1Comments
}
if(FORM006.Q1Answer.options[FORM006.Q1Answer.selectedIndex].value=="No"){
// validate Q1Comments
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of atljarman
atljarman

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just got lucky and found the right example.