0

I have this Javascript variable :

var Item_properties = {
   id : null,
   keys : [],
   hydrate: function() {
       //get data
       this.id = $('input[id=id]').val();

       $("#item_key div input").each(function(index) {
          this.keys.push($(this).val());
       });
}

It is impossible to push any data in keys array, I'm getting the message : Cannot call method 'push' of undefined

Any idea ?

0

3 Answers 3

7

jQuery sets this to the DOM element in the callback to .each. You can save this into a variable and then use it.

var self = this;
$("#item_key div input").each(function(index) {
  self.keys.push($(this).val()));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try like this:

var $this = this;
$("#item_key div input").each(function (index) {
    $this.keys.push($(this).val());
});

Your code didn't worked since the this inside the each loop was actually reference to the input tag. But you need to reference the Item_properties here.

Comments

0

While two other answers are ok, here is another way to do it.

You can use

Item_properties.keys.push($(this).val());

Instead of

this.keys.push($(this).val());

Comments

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.