使用JavaScript从URL参数填充隐藏字段

时间:2015-07-24 13:57:32

标签: javascript html forms url hidden

我正在尝试使用此JavaScript代码填充隐藏字段:

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

表格如下:

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

任何提示?

1 个答案:

答案 0 :(得分:0)

使用函数next函数获取url参数: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, " "));
}

如果您希望在加载页面时填充隐藏字段。然后将以下代码放在文档的末尾,就在或者你的main.js文件结束之前

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

jQuery 解决方案:

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