简体   繁体   中英

Pull Custom Query String Variable into Hidden Form Field Using Javascript

I am trying to pull a URL query string variable into a hidden form field to submit with an email opt-in.

The URL looks like this: http://domain.com/page/?tid=123456

I am able to pull the tid query string as I require with this code:

<script>
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1] || ''
    );
}

But I don't know how to place getURLParameter('tid') in the hidden field.

I have tried inline script but it looks like this doesn't work with Javascript.

<div id="optin">
<form id="em-optin" class="moonray-form-clearfix" action="https://forms.moon-ray.com/v2.4/form_processor.php?" onsubmit="return validateForm();" method="post" accept-charset="UTF-8" _lpchecked="1">

    <div style="display: none;">
        <input name="subid_198" class="moonray-form-input" type="hidden" id="mr-field-element-1" value="<script>getURLParameter('tid')</script>">

    <input name="email" type="text" class="email" value="Enter Your Email:" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" tabindex="501">
    <input type="submit" name="submit-button" value="Sign-up Now!" class="submit" id="mr-field-element-4" tabindex="502" "=" ">
</form>
</div>

Is anyone able to advise how I do this?

Hipporter. Have you tried to assign the value by using the following code:

var your_var = getURLParameter(name);
document.getElementById('mr-field-element-1').value = your_var;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM