Jquery:如何使用现有的输入文本值而不使用"change"、"keyup"等交互



这是用于显示输出的jquery代码..但是我在输入文本中使用现有值。 因此,可以显示数据,但我需要单击文本框并在文本框内进行更改以显示数据库中的项目。

我不想更改文本框值。

$(document).ready(function(){
$('.search-box2 input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal2 = $(this).val();
var resultDropdown2 = $(this).siblings(".result2");
if(inputVal2.length){
$.get("ajax2.php", {term: inputVal2}).done(function(data){
// Display the returned data in browser
resultDropdown2.html(data);
});
} else{
resultDropdown2.empty();
}
});
$(document).ready(function(){
const val = $('.search-box2 input[type="text"]').val();
$.get("ajax2.php", {term: val}).done(function(data){
// Display the returned data in browser
resultDropdown2.html(data);
});
});

只需随时查询输入并通过value属性获取其值:

// VanillaJS™ variant
const value = document.querySelector('.search-box2 input[type="text"]').value;
// jQuery variant
var value = $('.search-box2 input[type="text"]').val();
$(document).ready(function() {
yourFunctionName(); /* calling function at first time */
$('.search-box2 input[type="text"]').on("keyup input", yourFunctionName);
// keyup and input will call the same function as well.
function yourFunctionName() {
//...   
}
});

注意:yourFunctionName— 它只是一个变量,其中包含函数代码。yourFunctionName()- 带括号 = 表示"运行函数"。

最新更新