Click to See Complete Forum and Search --> : Can't use return value with Mozilla addEventListener


Migrate
07-22-2004, 04:18 AM
Good Morning.

I'm trying to create a input form element that accepts only numbers.

To accomplish this I add a event listener in Javascript to the input element (by using attachEvent for IE6 and addEventListener for Mozilla), but the function return value is ignored in Mozilla Firefox 0.8 (it works in IE6).
If instead of using the addEventListener I use directly the onkeypress event in the element it works correctly ( onkeypress="return mask(event)").

Can anyone tell me who to overcome this problem?

Here is the code:


<label for="myInput">Atacht Event in Javascript</label>
<input type="text" id="myInput" name="myInput">
<br>
<label for="myInput">Atacht Event in input</label>
<input type="text" id="myInput2" name="myInput2" onkeypress="return mask(event)">

<script>

attachEvent();

function attachEvent() {
var inputElem = document.getElementById("myInput");
// for IE 6
if (document.all) {
inputElem.attachEvent("onkeypress", mask);
}
// for Mozilla
else {
inputElem.addEventListener("keypress", mask, false);
}
}

var reValidChars = /\d/;

function mask(objEvent) {

var iKeyCode, strKey, objInput;
iKeyCode = objEvent.which;

if (document.all) {
iKeyCode = objEvent.keyCode;
objInput = objEvent.srcElement;
} else {
iKeyCode = objEvent.which;
objInput = objEvent.target;
}

strKey = String.fromCharCode(iKeyCode);
if (!reValidChars.test(strKey)) {
return false;
}


}
</script>



Thanks in advance.

Pittimann
07-22-2004, 05:32 AM
Hi!

This does not overcome the problem with 'addEventListener', but enables you to deal with your stuff in a way similar to the one you want:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<body>
<label for="myInput">Atacht Event in Javascript</label>
<input type="text" id="myInput" name="myInput">
<br>
<label for="myInput">Atacht Event in input</label>
<input type="text" id="myInput2" name="myInput2" onkeypress="return mask(event)">
<script type="text/javascript">
attachEvent();
function attachEvent() {
var inputElem = document.getElementById("myInput");
// for IE 6
if (document.all) {
inputElem.attachEvent("onkeypress", mask);
}
// for Mozilla
else {
inputElem.onkeypress=new function(){return mask;};
}
}
var reValidChars = /d/;
function mask(objEvent) {
var iKeyCode, strKey, objInput;
if (document.all) {
iKeyCode = objEvent.keyCode;
objInput = objEvent.srcElement;
} else {
iKeyCode = objEvent.which;
objInput = objEvent.target;
}
strKey = String.fromCharCode(iKeyCode);
if (!reValidChars.test(strKey)) {
return false;
}
}
</script>
</body>
</html>Cheers - Pit

Migrate
07-22-2004, 05:45 AM
Hi Pittimann.

Thanks for the quick answer. That resolved my problem.

Best Regards,
Migrate

Pittimann
07-22-2004, 05:48 AM
Hi!

You're welcome!
Have a good day.

Regards - Pit