i have a few li’s:
<ul>
<li class="one">
<input type="text" class="form_input" placeholder="Type something...">
</li>
<li class="two">
<input type="text" class="form_input" placeholder="Type something else...">
</li>
</ul>
i am trying to create a array similar to:
[
0[
'placeholder' : 'Type something...'
]
1[
'placeholder' : 'Type something else...'
]
]
i use a method like this
var lineText = function(elements) {
var myData = new Array();
elements.each(function(index, data) {
var li = $(this);
myData["placeholder"] = li.find('.form_input').attr("placeholder");
console.log(data); returns the li objects
});
console.log(myData);
};
from this i get [placeholder: "Type something..."], basically one item in my array, instead of 2
i can’t use push like this:
myData["placeholder"].push(li.find('.form_input').attr("placeholder")); //Cannot call method 'push' of undefined
or add another dimension to the array
myData[index]["placeholder"] = li.find('.form_input').attr("placeholder"); //Cannot set property 'placeholder' of undefined
any ideas? thanks
It sounds like you want an array of “associative arrays”. In JavaScript instead of associative arrays you can make objects can behave the same way. Meaning your above array would look like this in literal syntax.
Where
a[ 0 ][ 'placeholder' ]will return the string'Type something...'. Since this uses objects, properties can’t be pushed because they require some key. Instead you would write something likea.push( { 'placeholder': 'Type more stuff...' } ).If you only plan to add placeholders to the array there’s no need in using objects, just make an array of strings like this.
But when using my first solution, your function would become
Live example here http://jsfiddle.net/vU36T/6/