Reputation: 283
So I have this simple form with 1 input field that populates the input field with a parameter from the url...
Here's the demo: https://output.jsbin.com/[email protected]
So as you can see, it populates the input field.
THE PROBLEM
I am using this form in a responsive page and there are 2 of these similar forms. As per the visitor's device, one of them gets hidden (display:none).
But this code only populates the first form's email input.
How can I edit the code so that it will populate all input fields with that particular class?
THE CODE
<input type='text' class='email_address' name='email_address' value=''>
var getmail = document.querySelector('input.email_address');
if (getmail) {
var t = document.location.href.split('?')[1];
if (t) {
var params = {};
var lst = t.split('&'), l = lst.length;
for (var i = 0; i < l; i++) {
var p = lst[i].split('=');
if (!p[1]) continue;
params[p[0]] = p[1];
}
if (params.getmail) {
getmail.value = params.getmail;
}
}
}
I tried document.querySelectorAll and document.getElementsByClassName but doesn't work with it...
Some direction please. :)
Thanks...
Upvotes: 0
Views: 198
Reputation: 5681
.querySelector
selects only first matching element whereas .querySelectorAll
selects all matching elements. So either make your css selector query such that it can become unique else use .querySelectorAll
and then filter to the required element.
var getmails = document.querySelectorAll('input.email_address');
if (getmails) {
var t = document.location.href.split('?')[1];
if (t) {
var params = {};
var lst = t.split('&'), l = lst.length;
for (var i = 0; i < l; i++) {
var p = lst[i].split('=');
if (!p[1]) continue;
params[p[0]] = p[1];
}
if (params.getmail) {
for(var i =0; i<getmails.length;i++)
getmail[i].value = params.getmail;
}
}
}
<input type='hidden' class='email_address' name='email_address' value='' >
<input type='text' class='email_address' name='email_address' value=''>
Upvotes: 0
Reputation: 112
you can get parameter value and populate inputs has class email_address & working with most major browsers.
Note: you should encodeURIComponent
params value to be safe and
function getParam(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var input = document.getElementsByTagName('input');
for(var i=0;i<input.length;i++){
if(input[i].className =='email_address'){
input[i].value = getParam('getmail');
}
}
Upvotes: 1