views:

44

answers:

3

This answer suggested i should put my data in JS instead of a textarea.

Thinking about it i could have scripts and do something like myarray[i]="data" where i is the index of my for loop. However when i click a div how do i find out what i is? I have used var data = $(this).parent('.parent').find('.valuestr').eq(0).val(); which is extremely simple. Should i use a script or should i continue to do it with a textarea? if i should use a script 1) Whats the easiest way to find i and 2) Is it bad pratice to have dozens or hundreds of <script> in my html? or i can go through the loop twice but i still dont know the easiest way to find i. I would have to store it somewhere or go through multiple tags and count them.

+1  A: 

jQuery has a data() function just for that.

You store arbitrary data related to some element like this:

$('#my_div').data('foo', 'bar');
$('#my_div').data('hello', 'world');

Then you retrieve it like this:

alert($('#my_div').data('foo'));  // alerts "bar".
alert($('#my_div').data('hello'));  // alerts "world".
Max Shawabkeh
Thats cool. Then i need to make a dummy div with an ID and use $('#that_id').data? hmm. sounds good but so far in that other question i think i should use a textarea
acidzombie24
The id is just an example. You can tie the data to any element, regardless of whether it has an ID. The element you get using `$(this).parent('.parent')` in your example can be used just as easily.
Max Shawabkeh
looks like i need javascript in the page to set the data to each element but that isnt terrible. accepted
acidzombie24
A: 

Since each DOM_Element is just an object, you can declare a variable in the object.

for(var i = 0; i < elements.length; i++)
{
   elements[i].i = i;
   elements[i].onclick = function(){
      alert(this.i);
   }
}
ItzWarty
then how do i find i in elements ...
acidzombie24
... what do you mean? elements is just a DOM_Element[]
ItzWarty
Oh i think i see. a custon onclick for each loop with a different i. hmmm...... I think i'll do it the original way with textarea and not use the suggestion of storing it in JS. That way i can have the code cache in a external js file instead of in my app logic/html
acidzombie24
+1  A: 

Answering the other part of your question:

2) Is it bad pratice to have dozens or hundreds of in my html?

It will depend on who you talk to, but in general, yes, I think it is. There's actually a push for html to be completely devoid of Javascript, save loading of .js files. For more info, look into unobtrusive javascript.

http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

JGB146
Good to know. In this case i am using it not as the behavior layer but as data. +1
acidzombie24