DEV Community

Robert
Robert

Posted on

Build a simple form with BuildHTML

If you like writing JavaScript, you can use it to build your HTML too. That is what BuildHTML does.

In this short guide, we will make a page with an email field, a bio field, and a Save button. The result is one HTML file you can open in a browser.

Install the package

You need Node.js 18 or newer. In a new folder, run:

npm install @trebor/buildhtml
Enter fullscreen mode Exit fullscreen mode

Create the page

Make a file called form.js and add this code:

const { page } = require('@trebor/buildhtml');
const fs = require('node:fs');

const doc = page('My first BuildHTML form');

const layout = doc.div().css({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  gap: '20px',
  padding: '40px',
  backgroundColor: 'lightblue',
});

layout.h1('Tell us about yourself');

const form = layout.form().css({
  display: 'flex',
  flexDirection: 'column',
  gap: '16px',
  width: '100%',
  maxWidth: '360px',
});

const email = form.field('Email address', {
  type: 'email',
  name: 'email',
  attrs: { autocomplete: 'email' },
});

email.input.required().placeholder('you@example.com');

const bio = form.field('Short bio', {
  type: 'text',
  name: 'bio',
});

bio.input.placeholder('A few words about you');

form.button('Save').attr('type', 'submit');

const message = layout.p('');

form.onSubmit(function (event) {
  event.preventDefault();
  document.querySelector('#save-message').textContent = 'Form submitted!';
});

message.attr('id', 'save-message').attr('role', 'status');

fs.writeFileSync('form.html', doc.render());
console.log('Created form.html');
Enter fullscreen mode Exit fullscreen mode

Run it with:

node form.js
Enter fullscreen mode Exit fullscreen mode

Then open form.html in your browser. Try entering an email address and pressing Save.

What is happening?

page() starts the HTML document. Methods such as div(), h1(), and form() add elements to it. The field() helper creates a labelled input, so you do not have to wire up the label by hand.

The onSubmit() callback runs in the browser. Here it stops the browser from sending the form and shows a simple message. This is only a demo: it does not save the email or bio. For a real app, send the data to a server or another service.

Finally, render() turns the page into HTML, and writeFileSync() saves it as form.html.

Why try BuildHTML?

I like that the page structure stays in plain JavaScript. You can use variables, functions, and loops to build pages. You can also start with a simple HTML file and add browser behavior when you need it. There is no separate frontend build step for this example.

If you are building a Node.js page, a small dashboard, or a quick prototype, give it a try. The BuildHTML guide has more examples, including state and page navigation.

Top comments (0)