Search code examples
javascripthtmlformsauto-populate

Populate Multiple Input Fields With Paramter From Url... (Half Working)


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/wohegu?getmail=max@email.com

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...


Solution

  • 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');
    }
    }