I have a user input with id userName and I am trying to get the user input text using $("#userName").val() after user has finished inputting the text in the textbox and then storing it in a variable (a directory path), however, I'm getting undefined for $("#userName").val(). I'm thinking that the undefined is occurring cause the text field is not ready at runtime, so I'm trying to set up a callback function to use in my directory path but i'm still getting undefined when I do console.log("This is the field name: " + getUserName()); Below is my callback function:
function getUserName(){ $("#userName").keyup(function(){ console.log(this.value); return this.value; }); } I am trying to use this in my directory variable here (the variable filePath is outside the function getUserName()):
var filePath = "/my/path/to/the/file/" + getUserName() + ".txt"; However, when I do this I am still getting undefined. Am I doing something wrong here?
Update:
name.html: <div class="subArea" id="pvDiv"> <p id="nameP">Name: <input id="userName" class="userInput" type="text" placeholder="Enter Name"> </p> </div>
getUserName()function doesn't actually return anything. It attaches an event handler for thekeyupevent to the element with the iduserNameand then exits, returningundefinedby default. The function that handles thekeyupevent returnthis.valueto, well, the event handling routine. If you wanted to get the user name in thegetUserName()function,return $('#userName').val();would work better.return this.valueis meaningless in this contextgetUserName()return$("#userName").val()or if you want to update the file path on each keystroke, simply putfilePath = "my/path/" + this.value + ".txt"inside yourkeyuphandler. Make sure you definefilePathoutside of the event handler so that it updates and is visible wherever you need it.