Filling an array with elements from different HTML attributes

I have about 1000 images and text fields with the same class name and custom attribute. Class names are the emoticon and the emoticon, respectively. Custom attributes are emo-tag and emo-ascii respectively.

Each image has its partner (text field) with the same content in its custom attribute.

Example:

emo-tag = "fx" // for images emo-ascii = "fx" // for textareas 

where x represents a number from 0 to 999.

My script captures image attributes and what I need without any problems. The problem starts when I try to get a textarea value that has exact attribute content, such as an 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>"); }); 

As I said, the code works, but the text field captured and placed into the array is only the first and all elements 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 Result:

 [ {"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":":("}, ... ... ... ] 
+5
source share
1 answer

Using $('.emoticonlist').attr("emo-ascii",emotag) , you set the attribute instead of getting the element where the attribute is emotag . ( http://api.jquery.com/attr/ )

Maybe try replacing the string

 var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val(); 

with

 var emoascii= $('.emoticonlist[emo-ascii=' + emotag +']').val(); 

( https://api.jquery.com/attribute-equals-selector/ )

+3
source

Source: https://habr.com/ru/post/1238448/


All Articles