On a product page, a customer can select from different variants. In a "select" element, all the variants are stored. This element is hidden with display none. So, users can select variants using all fancy things like swatches and other fun stuff but under the hood its just a "select" element which keeps track of which variant is being used. Its value is variant id.
I am attaching an image to be more clear on what's going on.
Goal: Get the variant id on change of variant.
Problem: I am unable to detect the change event on this select element.
Limitations: I am not allowed to touch the HTML of this code. I can only append a javascript file at run time on this page in <head>
tag and I need to detect the change event in that script.
$(document).ready(function(){
$('body').on('change', "select[name='id']", function(){
console.log('here');
});
});
I can get its value just fine with below code at any time I want.
console.log($("select[name='id']").val());
Any ideas that why change event won't be detected?
As per the jQuery documentation change()
is not fired when val()
is set programmatically
Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.
You need to do it manually when you set val()
$("select[name='id']").val(354).trigger('change');
Edit[0]: After your comments on what you were trying to do I took a quick look at the js
.
I found that the template
fires a custom event variantChange
$("#ProductSection--product-template").on("variantChange", function(evt){alert($("select[name='id']").val());});
Good Luck;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With