简体   繁体   中英

Using JavaScript to populate a hidden field from URL parameter

I'm attempting to populate a hidden field with this JavaScript code:

var msg = window.location.href.match(/\?FieldName=([^#?&]*)/);
if (msg) {
    document.getElementById("FieldID").value = decodeURIComponent(msg[1]);
}

Form looks like this:

<form onsubmit="return Confirm2.render('Are you sure?');" parentpageid="####" siteid="####" pageid="####" action="formurl.com/" method="post" id="formid">
    <input type="hidden" id="FieldID" name="FieldName" VALUE="" /> 
</form>

Any tips?

Use the function next function to get url parameter: How can I get query string values in JavaScript?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

If you want the hidden field is filled when you load the page. Then place the following code at the end of your document, just before the end of the or your main.js file

(function () {
'use strict';
    var value = getParameterByName('FieldName');
    if (value !== '')
        document.querySelector('#hiddenField').value = value;
})();

jQuery solution:

$(function () {
    var value = getParameterByName('FieldName');
    if (value !== '')
        $('#hiddenField').val(value);
});

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