2

I'm using JavaScript to try and pass the value of a hidden input field as a variable into the url path below, but when I inspect the code, I'm seeing 'undefined' where I want the variable to be.

I would really like to get this issue solved. Any idea why the value is 'undefined' instead of the value of the hidden input field?

var userID = "";
userID = $('#userID').val();

document.write("<input type='hidden' id='userID'>");
document.write("<a href='http://sample/folder/" + userID + "/Documents/Forms/All.aspx'><li>test</li></a>");
R3tep
  • 12,512
  • 10
  • 48
  • 75
Marlon
  • 111
  • 2
  • 11
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon May 11 '16 at 13:56
  • 1
    As a start, your missing `;` on line 1 and secondly #userID probably doesn't exists on your page. – andybeli May 11 '16 at 14:00

3 Answers3

1

You're getting undefined because the input field doesn't have any value. Make sure you set a default value to the field so that even if nothing is entered into the field, you can still extract a value.

<input type='hidden' id='userID' value="defaultText"/>

Reference (JSFiddle): https://jsfiddle.net/e7zkhhny/ Side-note: It's usually a good idea to put a placeholder on an input field.

ykadaru
  • 1,108
  • 2
  • 16
  • 32
1

Your javascript can't find the value because your html is not created.

Try to create it, before getting the value.

document.write("<input type='hidden' id='userID' value='user1234'>");

var userID = "";
userID = $('#userID').val();
console.log(userID);

document.write("<a href='http://sample/folder/" + userID + "/Documents/Forms/All.aspx'><li>test</li></a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
R3tep
  • 12,512
  • 10
  • 48
  • 75
1

You're trying to retrieve a value from an element that does not yet exist on the page. It will exist only after this statement runs document.write("<input type='hidden' id='userID'>");

To work around this,

1) Make sure that the javascript runs only after the hml loads using a $( document ).ready(function() {

$( document ).ready(function() {
    var userID = ""
    userID = $('#userID').val();

    $('#link').attr("href", "http://sample/folder/" + userID + "/Documents/Forms/All.aspx");
}

2) Place the following html on your site:

<input type='hidden' id='userID' value="0">
<a id='link' href=''><li>test</li></a>
bastos.sergio
  • 6,684
  • 4
  • 26
  • 36