How to detect if a submit button has been clicked?

Hi, I’ve been trying to make a script that detects if a submit button was clicked. I’ve tried <button onclick> and addeventlistener but it’s not working.

hey! a couple of things you could check:

  1. the js file has been linked and has the correct name
  2. the function name that you’re adding is correct
  3. when you use <button type="submit"> it usually refreshes the form, try printing something on the console.log to ensure that the activity has been performed. or, try changing it to <button type="button">

hope this helps! :keyboard:

But I want it to detect if a form has been filled out before it activates the button. Is that possible?

Those are very general questions. If there is a typo it most likely won’t work. There are lots of JavaScript resources that demonstrate forms handling, validation, etc. and much of what is available would be influenced by what JS libraries you are using. You might check w3schools which has a “try it yourself” work area onclick Event you can experiment quickly.

I guess you can use required attributes

Yeah but if I use on click it activates even if the user hasn’t filled out the form.

I used required

Because that is the default behavior. I assume nobody here has seen the code so anything could be the issue. Do you want “just filled in” or meaningful answers? There are too many questions to guess what the issue might be. Did you search the hundreds of tutorial JS websites re: forms? I think the answer is in one of them.

Can I take a look at your code?

I use something like this, I use a POST endpoint to send form data when the button is hit and the required values are used. The thing is, you don’t need that stuff. You don’t need onclick, and also your backend should handle the rest when it receives the form info. Check out my example: https://required-inputs.glitch.me/.

By the way, don’t call me a cheater for using PHP. :stuck_out_tongue_winking_eye:

That’s an important part of event handling: your handler code usually runs before the browser performs a “default action” and has an opportunity to prevent that action.

document.getElementById('myform').addEventListener('submit', (event) => {
  const satisfactory = /* ... check various things */;
  if (!satisfactory) {
    // The default action for submitting a form is to
    // send the data to the server. Prevent that under
    // this condition.
    event.preventDefault();
  }
});

What do I put in the satisfactory value?

mostly a bunch of comparisons to see, as you describe, whether the form is filled out. other than the question here about detecting when the form is being submitted, are you comfortable with writing a routine to check if the form is filled?

The form knows when it’s filled because I used required

cool, does this mean you have it working as desired?

It works! Thanks!