4

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.

1
  • var errorMessage = "ErrorMessage" does have a ; at the end in the working code. Typo in this question Commented Feb 6, 2009 at 4:12

3 Answers 3

7

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;
Sign up to request clarification or add additional context in comments.

1 Comment

my only suggested improvement is to just use {} instead of new Object()
1

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.

Comments

0

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"></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>

3 Comments

lack of ; is a typo in the question ( doesn't exist in real code). Am using FF
This example is wrong. If you had set var name = "blork" (name is intended to be arbitrary), the example would fail.
@Justice thanks. I updated it to an example that works. but the other answers are better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.