Populating array with items from different HTML attributes
I have about 1000 images and textareas with the same class name and a custom attribute. The classes names are emoticon and emoticonlist respectively. The custom attributes are emo-tag and emo-ascii respectively.
Each image has its partner (a textarea) with the exact same content in its custom attribute.
Example:
emo-tag = "f-x" // for images
emo-ascii = "f-x" // for textareas
where x represents a number from 0 to 999.
My script captures the images attributes and what I need with no problem. The problem starts when I try to get the value of the textarea which have the exact attribute content like the image.
Here is my code:
$(function(){
var json = [];
$('img').each(function(){
var emoimg = $(this).attr("src");
var emoalt = $(this).attr("alt");
var emotag = $(this).attr("emo-tag");
//Does not this supposed to capture the value of this specific textarea?
var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();
json.push({
id : emotag,
name : emoalt,
img : emoimg,
content: emoascii
});
});
var s = JSON.stringify(json);
$("#content").after("<div>" + s + "</div>");
});
Like I said, the code works but the textarea captured and pushed into the array is just the first one and all the items of the array. How can I accomplish what I want?
Current Output:
[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":)"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":)"},
...
...
...
]
Desired Output:
[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":D"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":("},
...
...
...
]
Answer
Using $('.emoticonlist').attr("emo-ascii",emotag)
, you're setting the attribute instead of getting the element where the attribute is equal to emotag
.(http://api.jquery.com/attr/)
Perhaps try replacing the line
var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();
with
var emoascii= $('.emoticonlist[emo-ascii=' + emotag +']').val();
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM