Reputation: 33
I made some elements with a for
loop and I wanted to get the value and the source, but it seems I can't.
I made a demo of what I did here.
My function seems to work only on the last element created by the for
loop.
$("#emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
Upvotes: 3
Views: 48
Reputation: 62536
id
attribute should be unique, so when you use jquery to get elements by their id (using #
) you will get only the first element.
You should use the classes instead:
$(".emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
Here is the update to your code:
var emval = [':D',':C','8)',':O',':)','._.',':heart:',':P',';P',';)',':(','.-.','-.-'];
var emsrc = ['http://emojipedia-us.s3.amazonaws.com/cache/18/2f/182fa3786046d170707fa46a257185cb.png','http://emojipedia-us.s3.amazonaws.com/cache/c5/a5/c5a5a52fa1633e19ab2648f23ab1ee37.png','http://emojipedia-us.s3.amazonaws.com/cache/c1/2c/c12c7f3797ed8fcdcbedffb2649abfb1.png','http://emojipedia-us.s3.amazonaws.com/cache/55/af/55af488f029266842c13a54d4c50fc11.png','http://emojipedia-us.s3.amazonaws.com/cache/be/22/be22105632cfc32abf7b24bed3924e12.png','http://emojipedia-us.s3.amazonaws.com/cache/ce/1a/ce1a33d6a4535ce73c8b2b899d51071b.png','http://emojipedia-us.s3.amazonaws.com/cache/3e/f0/3ef0aeaf797844b672df6198c53ba479.png','http://emojipedia-us.s3.amazonaws.com/cache/43/be/43be98eee74f44eddec9c3137b1edf28.png','http://emojipedia-us.s3.amazonaws.com/cache/7e/d5/7ed517c9f335c3171b6f92685514667a.png','http://emojipedia-us.s3.amazonaws.com/cache/58/be/58be1ae13dbf3fb471f7f598a0365734.png','http://emojipedia-us.s3.amazonaws.com/cache/0c/04/0c04f9fd77dc486724c269587028e7d2.png','http://emojipedia-us.s3.amazonaws.com/cache/e6/7c/e67c860bd5cd2b9b443516171ec3c6a3.png','http://emojipedia-us.s3.amazonaws.com/cache/c1/05/c105ab901e2fa6e67b38879bcc0ac0b0.png'];
$(document).ready(function () {
for (var i = 0; i <= 12; i++) {
img = $('<img class="emprev" width="32px" height="32px" style="margin-bottom:3px;margin-left:4px;margin-top:2px">')
img.attr("value", emval[i]);
img.attr("src", emsrc[i]);
$("#emoji-list").prepend(img)
}
$(".emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="emoji-list" style="display:block;width:290px;height:200px;background:#ecebeb;border:1px solid black;border-radius:5px;position:absolute;bottom:150px;left:52%;z-index:9999999"></div>
Note that I also made some small changes to your code to make sure everything there works correctly
Upvotes: 4