I have variable
var student_office_id = $(this).data('office');
and I am looking to use it in the jQuery validate plugin like so:
$('.office_directed_to, .degree_type').bind('change', function() {
var student_office_id = $(this).data('office');
$("#admin-form").validate({
rules: {
"h_number["+student_office_id+"]": {
required: function(element) {
return $("#office_directed_to-8").val() != '';
}
},
"degree_type["+student_office_id+"]": {
required: function(element) {
return $("#office_directed_to-"+student_office_id+).val() != '';
}
}
} // end rules
}); // end validate
}); // end bing change
I receive the following error in the console: Uncaught SyntaxError: Unexpected identifier
It refers to the first line I try to append student_office_id in, I imagine it would return an error on the other instances too.
You can’t specify keys in objects using variables in that way. You’ll need to do the following:
The key point is that you can use the array-like
[]syntax with strings for accessing properties on objects, which will allow you to dynamically generate the key (as a string) using another variable’s value.