Generic way to get the value of an input regardles

2019-06-18 19:07发布

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?

2条回答
走好不送
2楼-- · 2019-06-18 19:19

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-18 19:28

Something like this:

var value = $('[type="radio"][name="option"]:checked, [type!="radio"][name="option"]', form).val() || '0'

Quite similar to Shankar's but does it all in the selector.

http://jsfiddle.net/infernalbadger/uUdX2/8/

It's not working when nothing is selected. Not sure what you want it to do when that happens?

查看更多
登录 后发表回答