0

I'm trying to understand a little of how the following html code snippet works under the hood:

<form action="/some_action" method="POST">
    <input name="name">
    <input name="email">
    <input name="password">
    <button> Sign Up</button>
</form>

I was expecting to find that button has some built-in onclick attribute that describes what it should do when it gets clicked.

I've tried inspecting the button and its respective form element with document.getElementByTagName() method and printing them to the browser's console with console.dir(), but hopelessly so far.

When the submit button is clicked, the GET request is triggered, but the button attributes and all other methods are empty strings when I inspect the document. It doesn't make sense to me. How the button does its job if it doesn't contain the information to do it?

Hope someone will help me so I can get on with my life : ]

5
  • This is the default behavior of HTML forms, when you define a <form> element with an action attribute, the browser automatically handles the form submission process. When you click the button, the browser collects the values of all form controls (inputs, textareas, selects, etc.) inside the form, then sends these values to the server specified in the action attribute using the HTTP method defined in the method attribute. you can learn more about the form element here: developer.mozilla.org/en-US/docs/Web/HTML/Element/form Commented Jun 20 at 21:11
  • If you want to do something else, you can take advantage of preventDefault() method to stop the form from submitting and do whatever you want. Commented Jun 20 at 21:13
  • It's probably more obvious what's going on if the button was written as <button type="submit">. The reason it still works without that type attribute is because submit is the default type for buttons.
    – Robert
    Commented Jun 21 at 0:48
  • @MHDAlaaAlhaj Thank you for your explanation. But I'm still intrigued though, because I've always assumed that once an element is rendered, all information regarding that element, including an existing onclick function, could be found by listing all the element's attributes with a console.dir(some_element) in the devTools console. So I'm confused that a button rendered within a form still presents empty strings, although it has some function associated with it anyway. I wonder how can I access that implicit onclick behavior.
    – Clodo
    Commented Jun 21 at 13:01
  • @Robert I think this answers my question. I can find it there on devTool's console! The type of the button as "submit". Since the button's form attribute is set with the form containing the button, it seems all information need is really there. Thank you!
    – Clodo
    Commented Jun 21 at 13:14

0

Browse other questions tagged or ask your own question.