jquery validate depends rule

Doug Hemingway picture Doug Hemingway · Nov 28, 2013 · Viewed 11.3k times · Source

I have a rule that appears to be formatted like the answer in this thread, but does not validate properly. If I comment out this rule, the validation is performed properly on the rest of the form. Other syntax errors I have found caused the same outcome, so I expect that there is a syntax error here, but durned if I can spot it.

The rule is

freq: {
    required: {
        depends: {function(element){
            return $('#freqBand').val().length > 0 &&
            $('#freqBand').val() != "24GHz");
            }
        }
    }
},

I am expecting that if the input field freqBand (a select input) value is anything other than "24GHz" or nothing, then the freq field is required.

I am just learning jquery, so it may be a real forehead-slapper.

EDIT 11/28

I have done some more troubleshooting and have found that $('#freqBand').val() is undefined.

it is found in the HTML as

<select  name="freqBand" tabindex="6">
        <option value="" label="&ndash;Choose&ndash;" >&ndash;Choose&ndash;</option>
        <option value="27MHz" label="27 MHz" >27 MHz</option>
        <option value="50MHz" label="50 MHz" >50 MHz</option>
        <option value="75MHz" label="75 MHz" >75 MHz</option>
        <option value="24GHz" label="2.4 GHz" >2.4 GHz</option>
</select>

The query validate docs say that the correct syntax for the select element should be

$("select.freqBand option:selected").val()

but that also resolves to undefined. Does this added information help someone to help me out?

Answer

aljo picture aljo · Oct 24, 2014

I know this is an old post but I'm currently running into a similar issue. That said, I'm concerned about the use of the id selector # for a name attribute. From what I've found, the id selector is in no way to be used for a name attribute, rather the name attribute should be addressed via the selector [name='name']

See: Name vs Id attribute in HTML

This probably doesn't fully solve your problem, but it would definitely be something to be aware of now rather than later. Again, I know it has been a year. Plus, if I'm right about the id selector for name attributes, then a huge issue with your code has been resolved.

Other than that, all of Joke_Sense's information is still true and relevant.

Oh, and I'm new to StackOverflow (though I haven't yet made an account I don't think). If anyone can give me feedback as to whether this response was... well it was meant to be just an aside. I'm just asking for constructive criticism. I've got the knowledge and know-how I just don't want to make a fool of myself.