簡體   English   中英

使用JavaScript從URL參數填充隱藏字段

[英]Using JavaScript to populate a hidden field from URL parameter

我正在嘗試使用以下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>

有小費嗎?

使用next函數獲取url參數: 如何獲取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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM