-3

I'm trying to get a value of property (or more) that user provides inside a for loop.


OBJECT:

RULES: { 
  "required": /.+/, 
  "numeric": /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/ 
}

FOR LOOP:

$("input").keyup(function() {

  var inputVal = $(this).val();
  var rules = $(this).data('rules').split(" ");

  for (var i = 0; i < rules.length; i++) {

     console.log(rules[i]); // OK - return "required" and "numeric"
     console.log(RULES.required); // OK - return "/.+/"

     console.log(RULES.rules[i]); // NOT OK

  };

});

MARKUP

<input data-rules="required numeric" type="text">

The problem is that it provokes an error: "Cannot read property '0' of undefined".

So how can I look for the value of "rule[i]" and not "rule[i]" itself? Why does not translate by itself?

Thank you in advance.

Boann
  • 48,794
  • 16
  • 117
  • 146
Mattos
  • 447
  • 2
  • 8

1 Answers1

1

you are doing:

RULES.rules[i]

you should do:

RULES[rules[i]]

when you do the first one, Javascript first looks for a rules property on the RULES object (but this property doesn't exist) then it tries to access element 0 of the rules property, which doesn't exist... hence you get "Cannot read property '0' of undefined" error

in the case where you want to access the property of an object using a variable for the name you cannot use dot notation any more and must use the square brackets

Anentropic
  • 32,188
  • 12
  • 99
  • 147