-1

I am trying to get values from data attribute (data-price) from different div on submit and put it into an array but can't get it working

var item_arr = new Array();

$('input[name^="item_price"]').each(function() {
  var MyVar = $(this).data('price');
  alert(MyVar);
  item_arr.push(MyVar);
});

console.log(item_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo-3" name="item_price[]" data-price="150"></div>
<div id="demo-4" name="item_price[]" data-price="175"> </div>
<div id="demo-5" name="item_price[]" data-price="125"> </div>

I expect the output to be item_arr = ["150","175","125"] currently it just return an empty array

Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114

2 Answers2

1

Your main issue is your selector: input[name^="item_price"]

You have input instead of div, because your element tags are type <div>.

Change it to: div[name^="item_price"]


Alternative jQuery approach

You can map the data value of every element and return a native array.

/** jQuery plugin */
(($) => {
  /**
   * Returns an array of data values for the selected elements.
   * @param {string} dataKey the data attribute key
   * @param {function} convertFn a post-processing function to convert the raw value
   * @return return an array of processed data values
   */
  $.fn.dataArray = function(dataKey, convertFn) {
    return this.map((i, el) => ((v) => convertFn ? convertFn(v) : v)($(el).data(dataKey))).toArray();
  }
})(jQuery);

console.log($('div[name^="item_price"]').dataArray('price', parseInt));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo-3" name="item_price[]" data-price="150"></div>
<div id="demo-4" name="item_price[]" data-price="175"> </div>
<div id="demo-5" name="item_price[]" data-price="125"> </div>
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
-1

Just change input[name^="item_price"] to div[name^="item_price[]"]. See below working code-

var item_arr = new Array();

$('div[name="item_price[]"]').each(function() {
  var MyVar = $(this).data('price');
  item_arr.push(MyVar);
});

console.log(item_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo-3" name="item_price[]" data-price="150"></div>
<div id="demo-4" name="item_price[]" data-price="175"> </div>
<div id="demo-5" name="item_price[]" data-price="125"> </div>
Shubham Baranwal
  • 2,333
  • 2
  • 12
  • 23