I'm trying to write a generic function I can use with the jquery validation plugin that will make a field required based on the value of another field. Here's what I want to happen:
Getting the value of Field 1 is the issue. I had no problem figuring this out with a text-type or <select>
input, but I'm trying to get it to work with radios and having 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 it to except radios, because it seems to read the value of the first radio, regardless of if it was checked or not.
The field that will trigger the "required" will either be one of the various text inputs (text
, url
, email
, etc.), a <select>
, or a single choice set of radios. No multiple choice. I'll be passing this function as a parameter to required
in my jquery validation config for each field I want it to apply to. The name
attribute of the "other" field that gets evaluated will be available to it.
Here's my demo so far, kind of ugly but there are notes: http://jsfiddle.net/uUdX2/3/
I've tried a bunch of different ways using is(':checked')
and the :checked
selector, but they have all failed. I removed them from the demo because they didn't work.
What do I need to get this working with radios and text-type or select inputs, without knowing which kind of input it will be?
Use the text() method provided by the TextEditingController to retrieve the String that the user has entered into the text field. The following code displays an alert dialog with the current value of the text field when the user taps a floating action button.
In JavaScript, the getElementById() and getElementsByClassName() methods are utilized to get the value of the text input field. In the getElementById() method, the input text box value is extracted with an ID attribute.
Try this
var value = $('[name="option"]');
var type = value.attr("type");
if(type && type.toLowerCase() == 'radio')
value = value.filter(":checked").val();
else
value = value.val();
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With