[英]how can i detect the last typed word from a text box
I want to detect the last typed word from a textbox. 我想从文本框中检测最后键入的单词。 For example if i type Test in the textbox for each keypress it should return the currently typed character.
例如,如果我在每个按键的文本框中键入Test,则它应返回当前键入的字符。
Here is what i am trying 这是我正在尝试的
$(".text").live("keyup",function(e)
{
var content=$('.text').val();
var lastIndex = content.lastIndexOf("");
var laststing = content.substring(0,lastIndex);
alert(laststing);
});
$(".text").on("blur", function (e) {
var content = $('.text').val();
var lastIndex = content.lastIndexOf(" ");
var laststing = content.substring(lastIndex);
alert(laststing);
});
I think blur event is a better option 我认为模糊事件是更好的选择
Use 采用
$(".text").live("keyup", function (e) {
var content = $('.text').val();
var lastIndex = content.lastIndexOf(" "); //Find last index of space
var laststing = content.substring(lastIndex); //Find rest of charcters
alert(laststing);
});
OR , You can use .split()
或者 ,您可以使用
.split()
$(".text").live("keyup", function (e) {
alert($(this).val().split(' ').pop()); //Simplest
});
use .on instead .live 使用.on代替.live
.live //jquery 1.3+ .live // jquery 1.3+
.on //jquery 1.7+ .on // jquery 1.7+
<script>
$(document).ready(function () {
$(".text").on("keyup",function(e)
{
var content=$('.text').val();
var lastIndex = content.lastIndexOf("");
var laststing = content.substring(0,lastIndex);
alert(laststing);
});
});
</script>
Try to use the function split()
, like this : 尝试使用
split()
函数,如下所示:
$(".text").on("keyup",function(e) {
var arrayString = $('.text').val().split(""); // Create an array with all characters
var lastString = arrayString.pop(); // Get the last character
alert(lastString);
});
This code provides the last character and not last word. 此代码提供了最后一个字符,而不是最后一个单词。
Reference 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.