1

This question is an extension of my SO question:

jQuery to disable/enable textarea depending on which radio button is selected inside of loop

I'm using the jQuery bassistance validation plugin (http://bassistance.de/jquery-plugins/jquery-plugin-validation/).

The validation rule I'm trying to create is if a radio button equals 'yes', then make the textarea a required field. My ID's and form field names for the radio and textarea boxes are dynamic but begin with the same word so I can use name^='travel'

HTML UPDATED

<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_1" data-travelNumber="1" id="travel_yes_1" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_1" type="radio" data-travelNumber="1" id="travel_no_1" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_1">
    <textarea name="travelDetails_1" id="travelDetails_1" ></textarea>
</div>

<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_2" data-travelNumber="2" id="travel_yes_2" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_2" type="radio" data-travelNumber="2" id="travel_no_2" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_2">
    <textarea name="travelDetails_2" id="travelDetails_2"></textarea>
</div>


<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_3" data-travelNumber="3" id="travel_yes_3" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_3" type="radio" data-travelNumber="3" id="travel_no_3" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_3">
    <textarea name="travelDetails_3" id="travelDetails_3"></textarea>
</div>

jQuery

//  I use this to hide/show the travelDetails textarea (show on yes, hide on no)
$('input:radio[name^="travel"]:checked').live('click',function(){
    var id = $(this).attr("id").split("_");
    id = id[id.length-1];
    $("#travelDetails_" + id).attr("disabled", !($(this).val() == "Yes"));
    if ( $(this).val() == 'Yes' ) 
        $('#Answer_travel_yes_' + id).slideDown();
    else
        $('#Answer_travel_yes_' + id).slideUp();
});


$("#TravelForm").validate({
        rules:{
            whatgoeshere:{
                    required: function(){
                        if ( $("input:radio[name^=travel]:checked").val() == "Yes" ){
                            //  make travel
                            true
                        }
                        else{
                            console.log('false');
                            true
                        }
          },
                    minlength: 10   // needs to have at least 10 characters entered (if the corresponding radio is Yes
            }
        },
        messages:{
            whatgoeshere:{
                required:"Please enter your travel details",
                minlength:"Please enter at least 10 characters"
            }
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
            //  $(element).parents('.control-group').addClass('success');
        }
    });
2
  • You have not really asked a question or explained very much about what you've already tried, what part is working, or what you still need help doing. You should also supplement this question with a jsFiddle demo. Commented Dec 21, 2012 at 19:01
  • I'm still somewhat unclear about what you're trying to do, but my answer should contain enough methods & documentation that shows how you can fix your code. Commented Dec 21, 2012 at 19:37

1 Answer 1

3

This is a generic answer which you can apply into your code...


I am fairly certain you cannot use a function inside the rules option. As per documentation, rules: need to be "key/value pairs", unless using the depends property.

rules: {
    mytextarea: {
        minlength: 10,
        required: {
            depends: function(element) {
                return $("#myradio:checked")
            }
        }
    }
},
messages: {
    mytextarea: {
        required: "Please enter your travel details",
        minlength: "Please enter at least 10 characters"
    }
}

mytextarea would be the value of the name attribute of your textarea.

<textarea name="mytextarea"></textarea>

Alternatively...

Apply jQuery .validate() rules dynamically.

First initialize your .validate() plugin with options:

$('form').validate({
    // your options, leave out the rule in question
});

Create a rules array (note the slightly different format when using messages):

var myrule = {
    required: true,
    minlength: 10,
    messages: {
        required: "Please enter your travel details",
        minlength: "Please enter at least 10 characters"
    }
}

Then within your conditional, target the textarea as required:

if ($(this).val() == 'Yes') {
    $('[name^="travel"]').rules('add', myrule);
} else {
    $('[name^="travel"]').rules('remove', myrule);
}

http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules


BTW, .live() has been deprecated in favor of .on().

Sign up to request clarification or add additional context in comments.

3 Comments

Regarding the .live(), old habits die hard. I keep forgetting about that one. I found a blog post about the function inside of the rule. If I can find it again, I'll post it here as an addendum. That said, I completely follow what you are saying so I'm go your route instead. Thank you!
@dlackey, I'm glad I could help. Keep in mind that you'll find many blog posts about using the .validate() plugin in ways that it was not intended as per official documentation. That being said, some of these things are perfectly valid methods, and some are just so verbose & obtuse, that the plugin just acts weird. So "buyer beware". (you can also search my profile for dozens of answers related to .validate plugin)
That is a lot of answers. I think someone knows their stuff! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.