在键入时或在输入失去焦点时将输入值保存到变量中

Saving an input value into a variable as you type, or as soon as the input loses focus

本文关键字:输入 保存 变量 失去 焦点      更新时间:2023-09-26

我研究这个问题已经有一段时间了,我想到的每个解决方案"几乎都有效"。理想情况下,我希望在输入时将输入值保存到变量中,这样我就不必在将输入值保存到变量之前执行任何命令。因为我无法找到解决方案,所以我一直在努力让它在输入失去焦点时立即改变。我试过。focusout,。change和。blur,但没有一个是在输入失去焦点的那一刻改变它。

//This will save the input value into the variable formInput
var formInput = $("#someForm input[type=text]").val();
//This successfully changes the value of formInput, but only after performing 
//another command, such as clicking go or pressing enter.  
//Tab does not count to the input "losing focus"
$("#someForm input[type=text]").focusout(function() {
$(this).val() = formInput.val();
});
// Same as focusout, as well as blur.
$("#someForm input[type=text]").change(function() {
$(this).val() = formInput.val();
});
//Nope.
$("#someForm input[type=text]").keyup(function() {
    formInput = $("this").val();
});

在现代浏览器中,监听input事件:

$("#someForm input[type=text]").on("input", function() {    
    formInput = $(this).val();
});

但是keyup处理程序也应该工作,如果你清楚你的困惑是否formInput是一个字符串值包含字段的值或一个jQuery对象链接到字段本身(如果formInput是一个字符串,它不会有val()方法)。

还有这个代码:

$("this")

选择所有<this>元素,如果返回任何东西,我会感到惊讶。

Try

var inputText;
$("#someForm input[type=text]").keyup(function() {
    inputText = $(this).val();
});