按下键即可获取textarea值 [英] Get textarea value once a key pressed

查看:43
本文介绍了按下键即可获取textarea值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在按键事件之后执行了一个函数:

I have an function executed after a keypress event :

$("#txtarea").keypress(function(){
    alert(document.getElementById("txtarea").value);
});

我想在每次按键后返回textarea的新文本,以便可以在其他javascript函数中同时使用它.

I want to return the new text of the textarea after every keypress, so that it can be used simultanuously in other javascript functions.

此脚本的问题在于,一旦按下一个键,该函数就会显示"空字符串.

The problem with this script is that once a key is pressed, the function displays "" empty string.

谢谢.

推荐答案

只是在分配值之前触发了按键.像其他所有事件一样(单击,提交等'...),因此您可以取消默认行为和填充"

The keypress just get fired before the value assigned. Like every other event(click, submit etc'...) so you can cancel the default behavior and "stuff"

$('#txtarea').keypress(function(event) {
    return false; // this will disable the new value assignment
});

您可以找到事件按钮单击了哪个按钮并对其进行处理.

You can find out what button was clicked with event.which and work with it.

示例:

<input id="txtarea" />​

$('#txtarea').keypress(function(e){
    var value = this.value; 
    alert(value);
    alert(value + String.fromCharCode(e.which))
})​;

JSFiddle演示

JSFiddle DEMO

您还可以使用 keyup 事件,但是它除了 keypress 以外,还有其他含义和用法.
请注意!

You can also use the keyup event, but it has other meaning and usage than keypress.
Be aware!

这篇关于按下键即可获取textarea值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆