92
<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 didn't 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)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TigerTiger
  • 10,590
  • 15
  • 57
  • 72

3 Answers3

232
  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);
toto_tico
  • 17,977
  • 9
  • 97
  • 116
  • 1
    I'm curious to know how this would look if using addEventListener? For Example would it look like this? buttonElement.addEventListener("click", check_me(event) ). – Code Novice Oct 09 '20 at 22:50
  • 2
    @CodeNovice with ``.addEventListener('click', check_me);`` the event is automatically passed as the first argument. So if you define your function like ``check_me(e){...}`` then you can use the event ``e`` in the function without an issue. Sometimes people construct it like this, but this is not needed ``.addEventListener('click', (e) => check_me(e));`` – Alex L Nov 12 '20 at 08:20
  • 3
    the question, and this answer by @toto_tico focus on what we call 'inline events', where the event handler is defined as a string, which is parsed and evaluated to a function call (or other valid JavaScript). You can just write a line such as ```` and this line would be executed. You can also define two functions like ``... onclick="check_me(event); another_func(event);"...`` if you really want to, and both would be executed. As well as the keyword ``event``, you can also pass ``this`` which is a reference to the calling element. – Alex L Nov 12 '20 at 08:32
28

Although this is the accepted answer, toto_tico's answer below is better :)

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
  • 295,876
  • 54
  • 310
  • 348
-4

I would change your binding to be:

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

I would then change your check_me() function declaration to be:

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(); 
     event.preventDefault(); 
   } else { 
    return true; }
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
John
  • 17
  • You can't just assume that "event" is defined. Your code gives me this runtime error: "ReferenceError: event is not defined". Sample code: function awesome() { console.info(event); } awesome(); – HoldOffHunger Nov 03 '17 at 15:21
  • @HoldOffHunger This function is supposedly to be called when an event occurs inline. Why would you call it directly, outside of an event. – Andrews Jul 09 '20 at 08:37