ChadT
ChadT

Reputation: 7693

jQuery Validator, programmatically show errors

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.

Upvotes: 4

Views: 7400

Answers (3)

bendewey
bendewey

Reputation: 40235

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>

Upvotes: 0

Sciolist
Sciolist

Reputation: 1829

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.

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827426

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;

Upvotes: 7

Related Questions