views:

1326

answers:

3

I can do something like this:

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

And that works fine, however if I try and do something like this:

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

It throws an 'element is undefined' error.

A: 

That should work fine. maybe the lack of a ; after the error message is throwing something off. What browser are your using?

This alert works fine on IE7

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

    </script>
</head>
<body>
</body>
</html>
bendewey
lack of ; is a typo in the question ( doesn't exist in real code). Am using FF
DaRKoN_
This example is wrong. If you had set `var name = "blork"` (name is intended to be arbitrary), the example would fail.
Justice
@Justice thanks. I updated it to an example that works. but the other answers are better.
bendewey
+2  A: 

What about:

var propertyName = "nameOfField";
var errorMessage = "ErrorMessage";

var obj = new Object();
obj[propertyName] = errorMessage;

validator.showErrors(obj);


Is worth to notice 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();
c.a = 0;
c.b = 1;
c.c = 2;
CMS
A: 

The reason you're getting an 'element is undefined' error there by the way, is because:

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

is equivalent to..

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

i.e., you're not assigning the value of propertyName as the key, you're assigning propertyName as a string to it.

Sciolist