jQuery AJAX api with variant radio buttons

Highlighted
Excursionist
45 0 12

I have a product with four options that are radio buttons. I am able to add each variant to the cart with a page refresh, but I want to be able to add it with AJAX.

I added the api.jquery.js to the theme.liquid file, and modified product.liquid with the following change:

<input href="#" type="submit" name="add" id="add" value="Add to cart" onclick="Shopify.addItem(jQuery('#{{variant.id}}').val());return false">

The problem is that it gives a 404 error due to the fact that it outputs all variants.

When I replace {{variant.id}} with one of my variants it works, obviously. 

How can I select just the desired radio option?

Thanks in advance,

Ben

 

Ben Klinger, Studio Ve
0 Likes
Highlighted
Shopify Partner
56 0 11

Ben,

If your already listing the radio buttons on the form, using a loop like this make sure the value is the variant.id

<select>
{% for variant in product.variants %} 
<input type="radio" name="{{ variant.title }}" value="{{ variant.id }}">
{{ variant.title }} - {{ variant.price | money }}</br>
{% endfor %}
</select>

Then have jQuery grab the selected radio button value (aka variant.id) into a variable "somevar"

This link shows how to do this: http://api.jquery.com/change/

then modify your code to send the variable with the call instead.  

....onclick="Shopify.addItem(jQuery(somevar).val());return false"...

Hope this helps...Cheers!

Efficiency through Simplicity is the only way to design...
0 Likes
Highlighted
Excursionist
45 0 12

Thanks, it worked!

now all I have to do is get rid of the alert that pops up once you add, and make the cart ajax as well.

Ben Klinger, Studio Ve
Highlighted
Shopify Expert
65 2 5

can share your code snippet code I can guide you. 

here is step you can add like that after ajax call. 

.ajaxSuccess(function(){
  alert("Your item added to cart");
});

 

0 Likes