I'm trying to write a generic function that I can use with a jquery validation plugin that will make a field mandatory based on the value of another field. Here is what I want:
- If the value of field 1 is specified in the given array of values ββ(currently testing "No", "n / a" and "0") or empty, do nothing. Otherwise, you must specify field 2.
Getting the value of field 1 is a problem. I have no problem with this if you enter text or <select> , but I try to get it to work with radios and with difficulty. Here is an excerpt from my code:
var value = $('[name="option"]').val(), empty = ['no', '', 'n/a', '0']; // If the input is not "empty", make the additional field required if ($.inArray(value.toLowerCase(), empty) < 0) { // returns -1 if not found required = true; } else { required = false; }
This works for everything I need, except for radio stations, because it seems to read the value of the first radio, regardless of whether it has been checked or not.
The field that will call "required" will be either one of various text inputs ( text , url , email , etc.), a <select> , or one set of radio stations. There is no multiple choice. I will pass this function as the required parameter in my jquery validation configuration for each field I want to apply to. The name attribute of the "other" field to be evaluated will be available to it.
Here is my demo so far, sort of ugly, but there are notes: http://jsfiddle.net/uUdX2/3/
I tried a bunch of different ways using is(':checked') and the :checked selector, but they all fail. I removed them from the demo because they did not work.
What do I need to work with radios and text types or the choice of inputs, not knowing what type of input will be?