Reputation: 1
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?
Upvotes: 0
Views: 4232
Reputation: 757
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);
});
Upvotes: 1