HTML HTML Forms Choosing Options Radio Buttons

Josh Olson
Josh Olson
13,062 Points

Can the amount of code in a form be minimized?

In the video, the amount of syntax used makes it hard to read any of the code. Each of these radio buttons requires an id, value, name, and a label with even more attributes. To pick out what the radio button does would require some digging. Considering how long forms can be, I'd rather use some other method.

            <label>Age:</label>  
            <input type="radio" id="under_13" value="under_13" name="user_age"><label for="user_13" class="light">Under 13</label><br>  
            <input type="radio" id="over_13" value="over_13" name="user_age"><label for="over_13" class="light">Over 13</label>

Questions,
Is there any way to simplify this code?
If not, how would you format this to make it more readable?
Also is there an HTML compiler (similar to the way Sass compiles CSS)?

2 Answers

Hey Josh,

Those attributes each have different roles they play for each element. The ID is for use with CSS and JavaScript. The name can be used by a server side language to get the value from the radio button. The value, and name, can also be retrieved by JavaScript, as well, for client side validation. There are two radio buttons, each with an appropriate label, that contain the values "under_13" and "over_13" respectively. For anyone who's been around HTML for a short period of time, it's easy to decipher what's going on here.

As far as formatting it for readability, it is in its most readable and simplest form. You should know what each attribute does for each element. Those are very basic attributes and will be seen constantly.

There are HTML minifiers such as this one but they only get rid of carriage returns and unnecessary spaces in your document, which will save some physical space but make the HTML much harder to decipher.

Late reply, but maybe someone will benefit.

If you don't use id for anything else than linking label with input you can place the input element inside the label element. That cleans things up a bit... like so:

<label><input type="radio" name="user_age" value="under_13">Under 13</label>
<label><input type="radio" name="user_age" value="over_13">Over 13</label>

Note that the order of label vs input can go either way and you can use this technique for all form elements. You might need to pay attention to any css that are dependent on the elements' placement in the dom.

Documentation @w3 ... see tips and notes.