Marlon
Marlon

Reputation: 111

Using Javascript to pass an input value as a variable

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

Upvotes: 2

Views: 212

Answers (3)

R3tep
R3tep

Reputation: 12854

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>

Upvotes: 1

bastos.sergio
bastos.sergio

Reputation: 6764

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>

Upvotes: 1

ykadaru
ykadaru

Reputation: 1144

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.

Upvotes: 1

Related Questions