开发者

Cancel a keypressed event throught handler function (addEventListener function)

I would like to create a test function which change the '.' charachter into ',' character in a text box. I cannot change the server side since it is google doc. '56.3' is considered as a number but '56,3' is (!).

Let's say that I have used the code below :

function changeValue(e) {
    e = window.event || e;
    var keyCode = e.charCode || e.keyCode;
    if (String.fromCharCode(keyCode)==='.') {
          event.target.value+=",";
          return false;
    }
    return true;
}

function start_up () {
    console.log('Start');
    var tmp = document.getElementById('ss-form');
    tmp = tmp.getElementsByTagName('input');
    console.log(tmp);
    for(var i=0; i<tmp.length; i++) {
    开发者_如何转开发        tmp[i].addEventListener('keypress',changeValue, false); 
            console.log(i, tmp[i]);
    }
};

window.addEventListener("load",start_up, false);

Then the problem is that both ',' and '.' are added to the field. How can I cancel the '.' pressed event? How can I replace the '.' pressed event by ',' pressed event?

I have searched the Internet and see no solution with the 'addEventListener' function.


Using e.preventDefault() should do it.

I got a jsFiddle demo put together: http://jsfiddle.net/yrYH4/


It may be because you are returning true from the event handler.

You can use event.preventDefault or return false to prevent default actions from being taken - you are returning false from the inner if statement of your handler, then returning true from the main function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜