0

I want to create a JS array that contains jQuery objects like this:

var oFormFields = new Object;
oFormFields.label = $(document.createElement('label'));
oFormFields.input = $(document.createElement('input'));

Since this crashes my code, i expect this is not possible. Any alternatives? This is my simplified version, I want to include some other properties so I'm able to re-use this in my code when building dynamic forms.

EDIT: Seemed this did work after all... what I wanted to do, was something like this:

var oFormFields = new Object;
oFormFields.name_field.label = $(document.createElement('label')).addClass('nam_field');
oFormFields.name_field.input = $(document.createElement('input')).addClass('nam_field');

This does break my code. I'm pretty new to jQuery, coming from a PHP background I'm having some troubles adjusting to the correct way to work with arrays / objects.

4
  • 5
    This code is working perfectly fine. It doesn't crash. But please, don't use "new Object" - use the literal version {}. Commented May 8, 2013 at 14:14
  • @JohannesLumpe Why shouldn't he use new Object out of curiosity? Commented May 8, 2013 at 14:25
  • Well it isn't doing any harm if that's what you're asking about. It's just that {} is more concise and in fact "new Object" and "{}" do exactly the same thing - the constructor is called behind the scenes if you use the literal version. In this case it's more about a clear coding style than about harm ;) Commented May 8, 2013 at 14:35
  • @bo-oz: your updated example breaks, because you are trying to set "label" and "input" on "name_field", which doesn't exist. If you had used the object literal like it's used in the accepted answer, you would have instantly noticed the error :) Commented May 8, 2013 at 14:37

2 Answers 2

5

Just use it like this:

var oFormFields = {
  label: $('<label />'),
  input: $('<input />')
};

You can create the element directly using jQuery. Furthermore, as mentioned in the comments, you should prefer the object literal notation over the new syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

@Mr_Green Yes, no reason why not. Object properties can be functions, and functions can return things. You'd obviously need to initialise oFormFields first, though.
Thanks.. I think the problem was I was using a different notation. I wanted to store all the labels and fields in one array. I'll update the code to reflect this..
1
var arr = [];
var oFormFields = {};
oFormFields.label = $('<label/>');
oFormFields.input = $('<input/>');

arr.push(oFormFields);
.........

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.