Magento 2 – Get Value of Selected Select Box in Custom Module

adminadminformjquerymagento2select

I have created a form using UI component, I want to retrieve value selected select box option on change.
I have created a requirejs-config.js file

var config = {
map: {
    '*': {
        customAdmin: 'Namespace_Modulename/js/customAdmin'
    }
},
deps: ["jquery"]
};

A custom js file

require(["jquery"], function ($) {
//your js code here
$(document).ready(function () {
alert('js loaded');
    $('select[name="custom_attr_name"]').change(function () {
        alert($(this).val());
    });
   });
});

I am getting an alert but not getting any value for the change of select box. When I run the same code on the console, everything works fine. I don't know whats wrong going on in this?
Please help me in identifying the issue.

Best Answer

Magento2 JS loads after the body is loaded. So whenever the page is loaded, the scripts are loaded simultaneously. You can try something like:-

require(['jquery'],
    function ($) {
        $(document).ready(function() {
            setTimeout(function(){
                  $('select[name="custom_attr_name"]').change(function () {
                      alert($(this).val());
                  });
              },5000);
    });
})

Or if it does not works try using body load inside the ready() function.

Related Topic