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?

2
  • 1
    Your form doesn't show up. Commented Jul 24, 2015 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. Commented Jul 24, 2015 at 14:26

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.