Through the URL, parameters come to me with values ​​that I write to the paramsURL [] array.
Then I need to set the incoming data as value for select.

$('select[name="brand"]').val(paramsURL['brand']); // этот select сгенерирован динамически. Поэтому jQ не может записать для него значение 

Question: How to set the value for a dynamically generated element?

All code:

 // Loading values to filter form $('#filterName').on('click', function () { // при клике на блок if (paramsURL['mtype'] > 0) { // проверяем есть ли значение для этого типа $('select[name="mtype"]').val(paramsURL['mtype']).trigger('change'); // задаем его из массива и устанавливаем триггер change. Здесь работает на Отлично! Потому, что это статически создаваемый select if (paramsURL['brand'] > 0) { // тоже самое с brand setTimeout(function() { // сделал костыль через setTimeout $('select[name="brand"]').val(paramsURL['brand']).trigger('change'); }, 5); // который сработает через 5мс } } }); 

Here's another job trigger trigger ('change');

 $('select[name="mtype"]').change(function () { $.ajax({ url: '/api/catalog/filter/brands?idtype=' +$('select[name="mtype"]').val(), method: 'GET', dataType: 'json', contentType: "application/json;charset=UTF-8", success: function (data) { var brand = $('select[name="brand"]'); brand.empty(); brand.append('<option selected disabled hidden>Марка</option>'); brand.removeClass('mark'); $.each(data, function(key, val){ brand.append('<option value="' +key+ '">' +val+ '</option>'); }); }, error: function(request, status, error) { var statusCode = request.status; console.log(statusCode); } }); }); 

  • one
    "this select is generated dynamically. Therefore, jQ cannot write a value for it" - by no means. Something you do not agree. - Igor
  • @Igor really, forgot to add the trigger code. Corrected! - Kobets Matviy 9:13 pm

1 answer 1

The value for the second select must be set after it is asynchronously filled.

 $('#filterName').on('click', function () { if (paramsURL['mtype'] > 0) { $('select[name="mtype"]').val(paramsURL['mtype']).trigger('change'); $('select[name="brand"]').data("value", (paramsURL['brand'] > 0)? paramsURL['brand'] : ""); } }); $('select[name="mtype"]').change(function () { ... $.each(data, function(key, val){ brand.append('<option value="' +key+ '">' +val+ '</option>'); }); if (brand.data("value")) { brand.val(brand.data("value")).trigger('change'); brand.data("value", ""); } ... }); 
  • It is necessary to read about such a property as .data ("value", val). I have never heard or seen before (: @Igor Mindful thanks for the help !! - Kobets Matviy