javascriptvariablesinputtextfieldgetparameter

How to input text into text field with javascript


I have a form on a wordpress site with a text field for an email adress which looks like this:

<div class="tnp-field tnp-field-email"><label>Email</label><input class="tnp-email" type="email" name="ne" required></div>

I can get the email address from a get parameter (www.domain.com/?email=test@mail.com) like this:

<script type='text/javascript'>
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

var emailtxt = getUrlParam('email','');

How can I fill the text field with emailtxt?


Solution

  • You can just set the value of the input field (HTMLInputElement.value = "value").

    document.querySelector("input[name=ne]").value = getUrlParam('email','');
    

    <div class="tnp-field tnp-field-email"><label>Email</label><input class="tnp-email" type="email" name="ne" required></div>
    <script type='text/javascript'>
    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = value;
        });
        return vars;
    }
    
    function getUrlParam(parameter, defaultvalue){
        var urlparameter = defaultvalue;
        if(window.location.href.indexOf(parameter) > -1){
            urlparameter = getUrlVars()[parameter];
        }
        return urlparameter;
    }
    
    var emailtxt = getUrlParam('email','');
     console.log(emailtxt);
    document.querySelector('input[name=ne]').value = emailtxt;
    </script>