JQuery Validator, show errors programmatically

I can do something like this:

validator.showErrors({ "nameOfField" : "ErrorMessage" }); 

And this works great, however, if I try to do something like this:

 var propertyName = "nameOfField"; var errorMessage = "ErrorMessage"; validator.showErrors({ propertyName : errorMessage }); 

It throws the error "element is undefined".

+4
javascript jquery
source share
3 answers

What about:

 var propertyName = "nameOfField"; var errorMessage = "ErrorMessage"; var obj = new Object(); obj[propertyName] = errorMessage; validator.showErrors(obj); 

It is worth noting that the following three syntaxes are equivalent:

 var a = {'a':0, 'b':1, 'c':2}; var b = new Object(); b['a'] = 0; b['b'] = 1; b['c'] = 2; var c = new Object(); ca = 0; cb = 1; cc = 2; 
+7
source share

The reason you get the "element" is an undefined error, because:

 var propertyName = "test"; var a = {propertyName: "test"}; 

equivalent to ..

 var a = {"propertyName": "test"}; 

ie, you do not assign the value of propertyName as a key, you assign it the name of the property as a string.

+1
source share

This should work fine. possibly the absence of a; after the error message throws something. Which browser are you using?

This warning works fine on IE7

 <html> <head> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script> <script type="text/javascript"> $(function() { var name = "name"; var value = "value"; var obj = eval("({ '"+name+"' : '"+value+"' })"); alert(obj[name]); }); </script> </head> <body> </body> </html> 
0
source share

All Articles