Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to get the value of an input regardless of type

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:

  • If Field 1's value is in a specified array of values (currently testing with "No", "n/a", and "0"), or is empty, do nothing. Otherwise, make Field 2 required.

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?

like image 418
Wesley Murch Avatar asked Aug 14 '11 20:08

Wesley Murch


People also ask

Which method is used to get value of a text field?

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.

Which function is used to get value from the input box?

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.


1 Answers

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

like image 128
ShankarSangoli Avatar answered Sep 21 '22 00:09

ShankarSangoli