Reputation: 35
I put 2 same data attributes in multiple elements (data-product-name & data-product-code), the intention is to populate the value from the data attribute in some input field.
<strong class="displayed_product_name" data-product-name="All content" data-product-code="abc">All content</strong>
I grab the data attributes values and make them as an array.
var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
arrProductCode.push($(this).text());
});
var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
arrProductName.push($(this).text());
});
To populate them in element and an input field
$(arrProductName).each(function () {
$('.pop_edit_country').find('.pop_edit_product_list ul').append("<li>" + this + "</li>");
});
$(arrProductCode).each(function () {
$('.hidden_edit_country_product_list').val($('.hidden_edit_country_product_list').val() + arrProductCode + ',');
});
The value of data-product-name grabbed correctly, but why the value of data-product-code is the same as data-product-name? I couldn't solve it, is it because 1 element cannot contain 2 data attributes?
Upvotes: 0
Views: 42
Reputation: 4919
This is because in the both case you call text
function instead of calling data
function.
text
function get the text context of your element while data
function gets the content of data attribute
you passed to it.
Here is the corrected code:
var arrProductCode = [];
$(this).closest('.each_content_item').find('[data-product-code]').each(function () {
arrProductCode.push($(this).data('product-code'));
});
var arrProductName = [];
$(this).closest('.each_content_item').find('[data-product-name]').each(function () {
arrProductName.push($(this).data('product-name'));
});
Upvotes: 1