1

I'm trying to set up an A/B test using Optimizely to change the color of the add to cart button on all product pages on the site.

Here's the current code on the site

<input id="id-for-test" class="add_to_cart_list" value="Add to Cart" name="Add to Cart" type="button"
                                                    onclick='sendToDataLayer("Category Lower", "Add to cart");return cat_add_one_to_cart( "<?= $p["id"] ?>", "<?= $param_sku ?>", "<?= $output_price ?>", "<?= $path ?>", "<?= $can_buy_limit ?>" ,"<?=$this_page_type?>")'/>

I'm adding this in the Optimizely code editor and it's not working

$('#id-for-test').removeClass('add_to_cart_list').addClass('color-test');
Amanda
  • 89
  • 1
  • 1
  • 8
  • It works on [JSFiddle](https://jsfiddle.net/j61m26u4/) – But I'm Not A Wrapper Class May 31 '16 at 18:12
  • You're right, it does work. But it doesn't work when I put it in Optimizely. – Amanda May 31 '16 at 19:01
  • Is there an error in the console? Does it find `$('#id-for-test')`? Do you run the code when the document is ready? – But I'm Not A Wrapper Class May 31 '16 at 19:04
  • I think I figured out the problem, but I don't have a solution. It's applying the color to the first item in all the categories. But it's not replacing the subsequent ones. I edited the fiddle so you can see the issue. – Amanda May 31 '16 at 19:07
  • If it works for the first but not the rest, sounds like it's because your above code will only target the element with the id ```id-for-test```. To target multiple elements you could use a shared class, for example. See these resources [here](https://help.optimizely.com/Build_Experiments/The_Code_Editor_and_Variation_Code#Changing_multiple.2C_similar_elements_at_once) and [here](http://stackoverflow.com/questions/31355393/jquery-selector-for-multiple-elements-of-one-ancestor). This works in jsfiddle [here](https://jsfiddle.net/4zba0064/). – Joel Balmer May 31 '16 at 19:52

2 Answers2

1

Give each cart input element a common class such as cart-class:

<input id="id-for-test" class="cart-class add_to_cart_list" value="Add to Cart" name="Add to Cart" type="button"
    onclick='sendToDataLayer("Category Lower", "Add to cart");return cat_add_one_to_cart( "<?= $p["id"] ?>", "<?= $param_sku ?>", "<?= $output_price ?>", "<?= $path ?>", "<?= $can_buy_limit ?>" ,"<?=$this_page_type?>")'/>

Then query based on class instead of ID:

$('.cart-class').removeClass('add_to_cart_list').addClass('color-test');

IDs are supposed to be unique, so the query just stops looking after it finds it's first instance. Use a class so it applies the change to all instances.

0

I think this should do the trick:

$('input.add_to_cart_list').removeClass('add_to_cart_list').addClass('color-test');
Beau
  • 1,771
  • 1
  • 15
  • 20