Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect change event on hidden select element

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.

visual description of question

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?

like image 286
awebartisan Avatar asked Sep 20 '18 20:09

awebartisan


1 Answers

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;

like image 148
Steve0 Avatar answered Sep 30 '22 06:09

Steve0