views:

812

answers:

2

Hi

<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)

A: 

You should have the event object there ready for use without having to pass it. This will work, depite the comment on the post. Try it

<input type="button" value="test" onclick="btn();" /> 
function btn() { 
    alert(event.type); 
}
James Wiseman
Not true, you have to pass it as an argument to the function
Marius
No you don't. Try it. Maybe you could be more explcit on how you would pass the event obejct in this manner?
James Wiseman
This code should work only in Internet Explorer which stores the event object in the "window.event" global. Any other browser follows the standard and pass the event object to the function directly.
Vincent Robert
Thanks Vincent for explaining why I was not correct. I'm going to leave it here so people can learn from my mistake.
James Wiseman
yes, i have to pass "event" as a parameter to get it working in firefox and IE
Wbdvlpr
+3  A: 

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();" />
Paul Dixon
not exactly what I was looking for .. but I'll mark it as answered. Thanks.
Wbdvlpr