HappyApe HappyApe - 3 months ago 6
Javascript Question

How to pass an event object to a function in Javascript?

<button type="button" value="click me" onclick="check_me();" />

function check_me() {
//event.preventDefault();
var hello = document.myForm.username.value;
var err = '';

if(hello == '' || hello == null) {
err = 'User name required';
}

if(err != '') {
alert(err);
$('username').focus();
return false;
} else {
return true; }
}


In Firefox, when I try to submit an empty value it throws up the error and sets the focus back to element. But same thing doesn't happen in IE as it throws up error and after clicking OK and posts the form (returns true).

How I can avoid this? I was thinking to avoid this using event.preventDefault(), but I am not sure how to do this using this method. I tried passing checkme(event) .. but it didnt work. I am using Prototype js.

(I know how to pass an event when I bind an .click function in javascript.. instead of calling onclick within html .. using Jquery, but I have to debug this piece of code)

Answer

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />