JavaScript Treehouse Club - MASH MASH - HTML Forms/Divs/Input

Reuven Kishon
Reuven Kishon
5,270 Points

Form questions

Hello there,

I have a few questions around the form tag that I hope you can help me with:

1) What is the purpose of the ID attribute? 2) Are there any attributes that get assigned a default value if you do not explicitly give them a value?

3 Answers

Josh Olson
Josh Olson
13,113 Points

What is the purpose of the ID attribute?

An ID attribute helps your CSS and Javascript find that particular tag. I know it looks ugly and redundant with the name attribute set as the same thing, i.e.

<input type="text" id="flavor" name="flavor">

But the name attribute along with its value is what gets sent whenever the user submits your form, not the ID attribute. Additionally a server will expect the name to have semantic meaning - it has to be named such and such. This is why your ID and name might not match.

You can do without an ID attribute if you don't have any CSS or Javascript that needs to directly find that tag.
You can do without a name attribute if you don't have any server-sided code reliant on that input.

Are there any attributes that get assigned a default value if you do not explicitly give them a value?

Currently there is no way to send a default value to a server. You can double check here.

Okay so what happens when you try to send a default value? From what I've seen writing backend servers with Node, your HTML might look like this.

<input type="text" name="user">
<input type="text" name="pass">
<input type="text" name="email">

And if the user filled out everything, you'll get JSON data back that looks like this:

{
"user":"joe",
"pass":"hunter2",
"email":"joe@website.com"
}

However If nothing was typed into the email field, you get this:

{
"user":"joe",
"pass":"hunter2"
}

Both the value and the name won't get sent. It's left to the server to decide what to do here. You can also do this client sided with Javascript and change the value before the form is submitted. Unfortunately there is no pure HTML solution.

Does that answer your questions?

Hi,

The purpose of the ID attribute is to be a unique identifier for a element. A class can be used on multiple elements, but an ID can only be used on one element.

Some examples of default attribute values:

textarea cols attribute - default is '20'

button type attribute- default is 'submit'

form target attribute - default is '_self'

Check out the MDN HTML Element reference - Pick a form element > Ctrl + F > 'default'.

Hope this helps :)

id is are more specific than a class selector