How to set a variant using jQuery [Debut]

macncheese
New Member
1 0 1

Is there a straightforward way to set a product variant in a select menu using jQuery so the user can add it to their cart? I already know the variant ID, select menu ID, etc. I simply want the user to be able to click on an element in the DOM and have a specific variant selected from the select menu when they do.

Here is my code so far. When you click on the element it retrieves the variant ID and title (stored as a data attribute via Liquid). But I don't know the next step, i.e., how to set that variant in the select menu. The select menu's id is SingleOptionSelector-0.

  $( document ).ready(function() {
    $('.product-single__thumbnails-item').click(function(){
      let id = $(this).attr('data-id');
      let title = $(this).attr('data-title');
      
      // SET PRODUCT VARIANT HERE
      
    })
  });

 

Help?

Thanks in advance!

ryanpwaldon
Explorer
51 6 12

Hey @macncheese,

Always a bit hard to suggest code without testing, but I'll have a go! Try this:

 

$(document).ready(function () {
  $('.product-single__thumbnails-item').click(function () {
    let id = $(this).attr('data-id');
    let title = $(this).attr('data-title');
    $('#SingleOptionSelector-0').value = title;
  });
});

 

If this doesn't work, send me a link to your website and I'll give it another shot : )

0 Likes