DEV Community


Posted on • Updated on

Creating an online budget tool 2/5

In my last post I showed how to layout the HTML for creating an online budget tool. In this post I am going to show how to add JavaScript to make the form dynamic.

First, I modify the add form at the top of the page by adding id’s to the input fields and the button. I also change the button to have a type of button to stop the form from submitting when the button is clicked.

          <input type="text" id="newItem">
          <input type="number" id="newAmount">
          <button id="addButton" type="button">Add</button>
Enter fullscreen mode Exit fullscreen mode

Next, I add an id to the table and remove the contents of the tbody.

        <table id="budgetTable">
Enter fullscreen mode Exit fullscreen mode

I then add a renderRow function to my Javascript:

const renderRow = (data) => {
  return `<tr>
Enter fullscreen mode Exit fullscreen mode

And a renderRows:

const renderRows = (data) => {
  const html = [];
  for (let i=0; i<data.length; i++) {
  return html.join('');
Enter fullscreen mode Exit fullscreen mode

Then I add a budgetItems array to the Javascript and also add an addBudgetItem function.

const budgetItems = [{
  item: 'Car',
  amount: 1.00

const addBudgetItem = () => {
  const budgetItem = {
    item: document.getElementById('newItem').value,
    amount: document.getElementById('newAmount').value
Enter fullscreen mode Exit fullscreen mode

I add a renderPage function that will link everything together to produce HTML for the table body and then assign the contents of the table body using the innerHTML property:

const renderPage = (id) => {
  document.getElementById(id).tBodies[0].innerHTML = renderRows(budgetItems);
Enter fullscreen mode Exit fullscreen mode

Finally, I add two event listeners, one called DOMContentLoaded that will call renderPage when the page loads and one being a click event on the add button to add a new item.

document.addEventListener('DOMContentLoaded', function($ev) {

document.getElementById('addButton').addEventListener('click', function($ev) {
Enter fullscreen mode Exit fullscreen mode

I can now start to keep track of all my subscriptions:

Clicking add will add a new item to the budgetItems array and then generate html to insert into the table body.


The biggest thing I had to remember when doing this was to use tBodies as spelt as it is case sensitive.

In my next post I will show how to create the total row and will start looking at how to style the form.

The code for the budget tool can be found here:

Discussion (0)