Open In App

Why Doesn't onclick="this.disabled=true;" Work in JavaScript?

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Using onclick="this.disabled=true;" in JavaScript can sometimes fail because the button's action is triggered before it gets disabled. This means the button's default behavior or associated action may still execute.

What Does onclick="this.disabled=true;" Do?

This code disables the button immediately after it is clicked by setting its disabled property to true. Once it disabled, the button cannot be interacted with again unless the property is manually reset to false. It is commonly used to prevent multiple clicks on a button.

How to Fix onclick="this.disabled=true;" Not Working?

To ensure the button disables correctly and prevents its default action, use JavaScript's addEventListener for proper event handling:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Disable Button on Click</title>
</head>

<body>
    <button id="myButton">Click Me</button>
    <script>
        document.getElementById('myButton').addEventListener('click', function (event) {
          // Disable the button
            this.disabled = true; 
           // Prevent default behavior if needed
            event.preventDefault();
            console.log('Button disabled');
        });
    </script>
</body>

</html>

Why This Works:

  • this.disabled = true;: Disables the button immediately after clicking.
  • event.preventDefault();: Prevents any default actions (like form submission).

This ensures the button is disabled before any other action occurs.

Why onclick="this.disabled=true;" Doesn't Always Work?

  • The button's default action (e.g., form submission or another event) gets executed before the disabled property is applied.
  • JavaScript applies disabled = true after the click event starts, allowing the action to proceed.

Next Article
Article Tags :

Similar Reads