user7070541
user7070541

Reputation:

Using jquery data attributes with each function

I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.

I'm using an each function to loop through all the products they add to sum the price.

For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!

HTML

<select class="form-control onChangePrice system1" name="SystemModel">
  <option value="">Select...</option>
  <option value="3300" data-min-price="3000">System 1</option>
  <option value="4500" data-min-price="4000">System 2</option>
  <option value="6000" data-min-price="5500">System 3</option>
  <option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
  <input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>

JS

 var systemTotal = 0;
 var systemMin = 0;
 var i = 0;
 $('.system1').each(function(){
  if (this.value != "") {
    systemEachMin = $(this).data("minPrice");
    console.log(systemEachMin);
    systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
    systemTotal += parseFloat(systemEachTotal);
    systemMin += parseFloat(systemEachMin);
  };
  i++;
});

The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!

Thanks

Upvotes: 0

Views: 1337

Answers (2)

PeteB
PeteB

Reputation: 134

$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.

this.options will return all the options in an array

or you could use the following for the selected options data attribute

$(this).find('option:selected').data("minPrice")

or

$("option:selected", this).data("minPrice")

Upvotes: 0

Alex
Alex

Reputation: 9041

You're doing a couple of things slightly wrong here:

$('.system1').each(function(){

should be:

$('.system1 option').each(function(){

and

systemEachMin = $(this).data("minPrice");

should be:

systemEachMin = $(this).data("min-price");

So in full:

var systemTotal = 0;
 var systemMin = 0;
 var i = 0;
 $('.system1 option').each(function(){
  if (this.value != "") {
    systemEachMin = $(this).data("min-price");
    console.log(systemEachMin);
    systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
    systemTotal += parseFloat(systemEachTotal);
    systemMin += parseFloat(systemEachMin);
  };
  i++;
});

Upvotes: 1

Related Questions