[英]Javascript grabbing user input field and using it in a variable
我有一个ID为userName
的用户输入,并且我试图在用户完成在文本框中的文本输入然后将其存储在变量(目录$("#userName").val()
之后使用$("#userName").val()
用户输入的文本。路径),但是,我对于$("#userName").val()
不确定。 我认为正在发生未定义的原因是文本字段在运行时尚未准备好,所以我试图设置一个回调函数以在目录路径中使用,但是当我执行console.log("This is the field name: " + getUserName());
下面是我的回调函数:
function getUserName(){
$("#userName").keyup(function(){
console.log(this.value);
return this.value;
});
}
我想在我的目录变量在这里使用这个(变量filePath
是功能外 getUserName()
var filePath = "/my/path/to/the/file/" + getUserName() + ".txt";
但是,当我这样做时,我仍然变得不确定。 我在这里做错什么了吗?
更新:
name.html:
<div class="subArea" id="pvDiv">
<p id="nameP">Name:
<input id="userName" class="userInput" type="text" placeholder="Enter Name">
</p>
</div>
由于许多原因,您的代码没有任何意义,其中大多数可以在问题下方的注释中找到。 简而言之:
您是在函数内部设置keyup
事件监听器,因此除非调用该函数,否则keyup
事件处理程序将无法工作,因为不会设置事件监听器。
您忽略了以下事实:事件处理程序的执行是异步操作,并且不返回任何内容。
即使以上可能,在getUserName
仍然没有return
语句。
尝试使用以下事件之一,并在事件处理程序内部构造路径:
blur
事件,当input
失去焦点时触发。 change
事件,当input
值发生更改时将触发此事件。 码:
$("#userName").on("change", function() {
var filePath = "/my/path/to/the/file/" + this.value + ".txt";
console.log("The new path is '" + filepath + "'.");
});
直接使用$("#userName").val()
获取输入值的问题可能是由于在执行该代码时DOM尚未准备就绪,或者您不等待某些事件发生,所以看看
并且输入上的Keyup事件处理程序未正确实现,因为它不会在您的函数中返回任何内容。
然后,取决于您要如何处理用户输入,便是您需要实现的解决方案,类似的事情应该起作用。
var filePath;
function updateFilePath() {
filePath = 'myPath/' + this.value + '.txt';
console.log('The file path has changed to: %s', filePath);
}
// When the dom Is ready to be used, you execute your code.
$(function() {
// Add an event handler when userName input value change
$('#userName').on('change', updateFilePath);
})
如评论中所述,您可以使用其他事件,例如“ keyup”,“ blur”或更适合您需要的任何事件,但是“ change”可能是您意图的最佳选择。
refreshAutoComplete
到您的目标元素。 $('#autocompleteResult').trigger('refreshAutoComplete', [{userData: this.value}]);
var filePath = "/my/path/to/the/file/" + data.userData + ".txt"; $(this).html(filePath);
此方法将职责分开:
现在,您的filePath
逻辑已分离,可以从JS应用程序的其他部分重复使用。
$(document).on('input', '#userName', function() { $('#autocompleteResult').trigger('refreshAutoComplete', [{userData: this.value}]); }); $(document).on('refreshAutoComplete', '#autocompleteResult', function(e, data) { var filePath = "/my/path/to/the/file/" + data.userData + ".txt"; $(this).html(filePath); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="subArea" id="pvDiv"> <p id="nameP">Name: <input id="userName" class="userInput" type="text" placeholder="Enter Name"> </p> <p id='autocompleteResult'> </p> </div>
您创建的功能只是将keyup事件绑定到文本框。 当您键入该函数时,该函数getUsername将被调用。
为了获得它的值,您可以使用$(“#userName”)。val()这样,您可以使用
var filePath = "/my/path/to/the/file/" + $("#userName").val() + ".txt";
如果仅在userName字段存在时才需要执行此操作,则可以执行以下操作:
if( $("#userName").length > 0)
filePath = "/my/path/to/the/file/" + $("#userName").val() + ".txt";
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.