简体   繁体   English

AJAX / JS:是否可以在没有提交按钮和刷新页面的情况下获取输入文本的值

[英]AJAX/JS: Is it possible to grab value of input text without a submit button and refesh page

I have searched countless of sites but havent come upon a definite answer. 我搜索了无数网站,但还没有得到明确的答案。 Maybe this is not possible. 也许这是不可能的。 But I am working with an input box that will echo its value once the user stops typing. 但是我正在使用一个输入框,一旦用户停止键入,它将回显其值。 I dont have relevant code since I want to find out if this possible? 我没有相关的代码,因为我想知道是否可能?

Here in this example I can submit trhrough a button and get the value without a refresh. 在此示例中,我可以通过按钮提交并获得值而无需刷新。 JSfiddle 的jsfiddle

But I would like to be able to not use the button. 但是我希望不能使用该按钮。

It's possible with a script, onkeyup and a timer . 可以使用脚本,onkeyup和timer

Basically what you do is when a user starts typing, you fire up a timer for a submit function. 基本上,您要做的就是在用户开始输入内容时为提交功能启动一个计时器。 Every time the user presses a key when the input is focused, you "postpone" the timer by clearing it and creating it again. 每次用户将焦点对准输入时,只要按下该键,就可以通过清除并重新创建计时器来“推迟”计时器。 Once the user stops typing, the timer won't be cleared and the function will run. 一旦用户停止键入,计时器将不会清除并且该功能将运行。

var timer;

$('#yourName').on('keyup', function() {
    var value = this.value;

    clearTimeout(timer);

    timer = setTimeout(function() {

        //do your submit here
        alert('submitted:' + value);

    }, 2000); //delay after a keypress
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM