Good day.

There is a JS code that gets a get-request from the URL (utm-tags) and inserts data into the input, for later sending to the letter form, if there is one. If you use getElementsById, then everything works fine. But the fact is that there are several forms on the page, so it is necessary to use the class, but getElementsByClassName does not work.

window.onload = function(){ var tmp = new Array(); // два вспомагательных var tmp2 = new Array(); // массива var param = new Array(); var get = location.search; // строка GET запроса if(get != '') { tmp = (get.substr(1)).split('&'); // разделяем переменные for(var i=0; i < tmp.length; i++) { tmp2 = tmp[i].split('='); // массив param будет содержать param[tmp2[0]] = tmp2[1]; // пары ключ(имя переменной)->значение } var objsource = document.getElementsByClassName('source'); // вывод на экран var objmedium = document.getElementsByClassName('medium'); var objcampaign = document.getElementsByClassName('campaign'); for (var key in param) { if (key == 'utm_source') { objsource.value += key+" = "+param[key]+"<br>"; } if (key == 'utm_medium') { objmedium.innerHTML += key+" = "+param[key]+"<br>"; } if (key == 'utm_campaign') { objmedium.innerHTML += key+" = "+param[key]+"<br>"; } } } } 

Well and, accordingly, three inputa:

  <input type="text" class="source" value="" /></div> <input type="text" class="medium" value="" /></div> <input type="text" class="campaign" value="" /></div> 

    1 answer 1

    getElementsByClassName() Returns a set of items.

    • I, unfortunately, is not very strong in JS, tell me how to be in this situation? - drm
    • @drm, in fact, you get an array with the found elements, because it is likely that the document may contain several elements with the same class. You can do it in several ways. The first is if it is known in advance that there is only one element, then just take the first element: objsource [0] .value = '...'; Or if there are several elements, then go through the loop: for (var i = 0; i <objsource.length; i ++) {objsource [i] .value = '...'; } - lampa
    • Yes, now I understand, thank you very much. - drm
    • @drm, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - lampa