0

I'm working on a Snipcart site where data attributes for prices on the .button element are updated based on radio buttons that are selected.

Currently what I have which is working fine is this:

HTML

<fieldset class="pill-container">
<legend>Choose your length of subscription</legend>
<label for="sub_length-3">
  <input type="radio" 
    name="sub_length" 
    id="sub_length-3" 
    value="3" 
    data-price="35" 
    data-total="105">
  <span>3 months</span>
</label>
<label for="sub_length-6">
  <input type="radio" 
    name="sub_length" 
    id="sub_length-6" 
    value="6" 
    data-price="33" 
    data-total="198">
  <span>6 months</span>
</label>
<label for="sub_length-12">
  <input type="radio" 
    name="sub_length" 
    id="sub_length-12" 
    value="12" 
    data-price="31" 
    data-total="372">
  <span>12 months</span>
</label>
</fieldset>

<span class="price">$<b>35</b></span>

<a href="#" 
  class="button" 
  data-item-id="XXXXX-3" 
  data-item-name="Name" 
  data-item-price="105" 
  data-item-description="3 months subscription">Add to cart</a>

JS

<script>
$("[name=sub_length]").on("change", function(){
  var sub_length = $(this).val();
  var description = sub_length + " months subscription";
  var price       = $(this).data("price");
  var total       = $(this).data("total");
  var currentID   = $(".button").data("item-id");
  var id          = currentID.substring(0, currentID.indexOf("-"));
      id          = id + "-" + sub_length;
  $(".button")
    .data("item-description",description)
    .data("item-price",total)
    .data("item-id",id);
  console.log("Description: "+$(".button").data("item-description"));
  console.log("Total: "+$(".button").data("item-price"));
  console.log("ID: "+$(".button").data("item-id"));
  $(".price b").html(price);
});
</script>

So when you change the radio buttons, the data-item-price on .button is updated and when you click on the button, that value is then added to the cart (which is how Snipcart works).

But now I have to introduce another select element which introduces different categories which have different prices which when changed will dynamically update the prices.

Currently the three subscription prices are set server side before being delivered to the template. Now those three prices can be changed based on the value of the dropdown below.

I thought I'd need to do something again with data attributes:

<select name="options" id="options">
<option value="">Please choose…&lt;/option>
<option 
  value="Option 1" 
  data-price_3="35" 
  data-price_6="33" 
  data-price_12="31">Option 1</option>
<option 
  value="Option 2" 
  data-price_3="25" 
  data-price_6="23" 
  data-price_12="21">Option 2</option>
</select>

but I'm not really sure about the best approach for combining what I already have with the new select element.

Can I have the one element change the data attributes of the other and have a script listen for silent updates as well as on.change/input?

4

0 回答 0