Dynamically Adding Fields with jQuery

Posted on Thu 27 January 2022 in Programming • Tagged with javascript, jQuery

The jQuery JavaScript library provides elegant solutions to various programming challenges. While browsing a jQuery email list, I came across a simple problem that even a novice JavaScript coder like me could tackle. I'll simplify it here for the sake of clarity. Essentially, the original poster wanted to add form fields to a table while incrementing a field counter in both the HTML and the ID and name tags. To add a bit more complexity, the field numbers needed to be padded with leading zeros. Adding table rows with jQuery is straightforward, and it turns out that adding leading zeros is quite simple too. I appreciate JavaScript's "everything is an object" approach, which even extends to built-in objects like the String object. Let's start with that.


The String object lacks a built-in method for repeating characters. After a quick internet search, I found an efficient solution. To pad leading zeros, we first need a method to repeat a character. Although this explanation may skip the details of how the prototype works, you might want to research it further.


// Add a repeat method to the String object

String.prototype.repeat = function(n)

    return new Array(n + 1).join(this);



Now we can use `'0'.repeat(3)` to generate a string of three zeros ("000").


Next, let's create a short padding routine. When writing code, it's wise to think ahead and consider whether you'll need similar functionality in the future. Can you make it dynamic? Here's the padding function I came up with:


// Add a leading_zeros function

var leading_zeros = function(n, total_digits)

    n = n.toString();

    return '0'.repeat(total_digits - n.length) + n;



To make this work with jQuery, I prefer to create a jQuery plugin. This allows us to add a method to the jQuery object, making it easy to …

Continue reading