Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel a keypressed event throught handler function (addEventListener function)

Tags:

javascript

dom

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.

like image 952
MUY Belgium Avatar asked May 15 '26 12:05

MUY Belgium


1 Answers

Using e.preventDefault() should do it.

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

like image 100
gilly3 Avatar answered May 17 '26 01:05

gilly3