0

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?

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
  • 1
    Your form doesn't show up. – Tania Rascia Jul 24 '15 at 14:10
  • If `msg` validates and `FieldID` is your hidden input’s id, setting the value should suffice. Question remains, what’s `Confirm2` doing? How’s your markup? Perhaps you should provide a [Fiddle](http://jsfiddle.net/). – dakab Jul 24 '15 at 14:26

1 Answers1

1

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);
});
Community
  • 1
  • 1
Chofoteddy
  • 747
  • 9
  • 22