开发者

javascript oncut bug?

In this code:

<!doctype html>
<body>
<input id="a"/>
<in开发者_运维知识库put id="b"/>
<script>
var a=document.getElementById("a");
var b=document.getElementById("b");
a.addEventListener("cut",function(e){
    b.value=a.value;
    //the line above is not working as expected!
    //neither does this (as per tjm's answer): b.value=a.value.substr(0,a.selectionStart);
},true);

</script>
</body>

When I do a cut in text-box-a, I want text-box-b to have the same value as text-box-a.. but it's not working. does anyone have any solution to this problem?

I need the solution to work in IE9.

(3 answers so far though none of them worked.. i can't believe we can't do this in javascript.. this is like one of the less-common-but-still-common stuff that we need ain't it?)


I think this works as you want it to.

<script>
var a = document.getElementById("a");
var b = document.getElementById("b");

a.addEventListener("cut", function(e) {

    var s = a.value;
    b.value = s.substr(0,a.selectionStart) + s.substr(a.selectionEnd);

}, false);

</script>


This is definitely not the best solution, but it works. You can probably lower the timeout to make it a bit better. This is a total hack. I just don't know anything else to advise.

a.addEventListener("cut", function(evnt) {
    setTimeout(function() {
        document.getElementById("b").value = evnt.srcElement.value;
    },100);
}, true);


You can try

a.addEventListener("beforecut",function(e){
    b.value=a.value;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜