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>");
2

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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>

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.