input+html+change,javascript - <input> text change events - Stack Overflow

I had a similar problem yesterday and came up with a solution to diff old and new text input values.

The output is like this:

Old value: test test

New value: test w

Change: overwrote 'test' with 'w' at position 5

The script uses window.setInterval() to avoid cross browser problems (see https://stackoverflow.com/a/1949416/727190). This causes some changes to be batched when the user types really fast - this could be a good thing, depends on your situation.

You can, however, easily modify the script to work off events.

Excerpt from fiddle showing the result of the diff (the findChange() code is too long to paste here):

var changeType = { added: 0, deleted: 1, overwrite: 2 };

var previousValue = '';

window.setInterval(checkChange, 100);

function checkChange() {

var newValue = $("#input1").val();

if(newValue != previousValue) {

showChange(findChange(previousValue, newValue));

previousValue = newValue;

}

}

function showChange(result) {

$("#last-change").html("Prev: " + previousValue + "
Next:" + $("#input1").val() + "
");

if(result == null) {

$("#last-change").html($("#last-change").html() + " no change detected");

return;

}

switch (result.change) {

case changeType.added:

$("#last-change").html($("#last-change").html() + "added '" + result.added.text + "' at position " + result.added.position + "
");

break;

case changeType.deleted:

$("#last-change").html($("#last-change").html() + "deleted '" + result.lost.text + "' at position " + result.lost.position + "
");

break;

case changeType.overwrite:

$("#last-change").html($("#last-change").html() + "overwrote '" + result.lost.text + "' with '" + result.added.text + "' at position " + result.added.position + "
");

break;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值