selectCallback variant selector, if variant.title contains?

Solved

selectCallback variant selector, if variant.title contains?

Djurmamman
Explorer
63 4 11

I need to show divs on product page based on selected variant.

I dont want to use variant.id == 'variant name' because its a lot of products with sometimes 3x3 options.

I'm not that good on JS so i cant make it work with contains operator.

 

var selectCallback = function(variant, selector) {
 if (variant) {
  if (variant.title contains 'banana') {
  $('.banana').css('display', 'block');
  } else {
  $('.banana').css('display', 'none');
 }
}

 

 

 

 

Accepted Solution (1)

gina-gregory
Shopify Partner
742 51 212

This is an accepted solution.

Try this:

var selectCallback = function(variant, selector) {
 if (variant) {
  var variantTitle = variant.title;
  if (variantTitle.indexOf('banana') !== -1) {
  $('.banana').css('display', 'block');
  } else {
  $('.banana').css('display', 'none');
 }
}

View solution in original post

Replies 2 (2)

gina-gregory
Shopify Partner
742 51 212

This is an accepted solution.

Try this:

var selectCallback = function(variant, selector) {
 if (variant) {
  var variantTitle = variant.title;
  if (variantTitle.indexOf('banana') !== -1) {
  $('.banana').css('display', 'block');
  } else {
  $('.banana').css('display', 'none');
 }
}
Mircea_Piturca
Shopify Partner
1548 44 346

As Gina mentioned, in JS you can use indexOf or includes, e.g.: variantTitle.includes('banana').

You may want to sanitize first the title string. Take care of whitespace or lower/uppercase variations.

Finally—Add variant descriptions to your products