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.

```javascript

// 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:

```javascript

// 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 use for padding. While this approach is not strictly necessary, I believe it results in cleaner and more usable code.

 

According to the jQuery Plugin Manual, we should start a new plugin with the following code block:

```javascript

(function())();

```

It's not immediately obvious that this function will run automatically, and this wasn't readily apparent in many online JavaScript references. Additionally, it may confuse some readers that the `$` character is not a legal character for a JavaScript variable name. However, after some investigation, I found an EcmaScript specification stating that `$` is valid as the first character in a variable name. As JavaScript variables can consist of just one character, `$` is indeed a valid variable name. This is also the name the library author chose for the jQuery object.

```javascript

(function($) )(jQuery);

```

With this in mind, we can continue with the code block.

 

Now, let's create a counter that utilizes a static variable. A static variable retains its value between function calls. In JavaScript, you simply declare the variable outside the function, and it behaves as a static variable.

```javascript

// Initialize the counter

var counter = 0;

 

var count = function()

    return ++counter;

;

```

Due to how scope works in JavaScript, the value of the variable `counter` is preserved between calls to the `count()` function, resulting in incrementing values in the alerts.

 

Finally, let's integrate this into the document-ready portion of our jQuery application.

```javascript

$(document).ready(function()

 

    // Initialize the counter

    var counter = 0;

 

    $('#fields-button').click(function()

 

        // Increment and pad the counter

        var padded_counter = $.leading_zeros(++counter, 3);

 

        // Create the new field

        var extrafield = '<tr><td>List Item ' + padded_counter + '</td><td>';

        extrafield += '<input type="text" name="' + padded_counter + '"'

        extrafield += ' id="' + padded_counter + '"></td></tr>'

 

        // Add the new field to the table

        $('#fields').append(extrafield);

    );

);

```

Bringing it all together results in the following:

```html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.dfwrein.com/html4-embed.dtd">

<html>

<head>

    <title>Dynamic Fields</title>

    <script type="text/javascript" src="/site/code/jquery-1.2.2.pack.js"></script>

    <script type="text/javascript">

 

        (function($)

 

            // Add repeat method to String object

            String.prototype.repeat = function(n)

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

            ;

 

            // Add leading_zeros method to jQuery

            $.leading_zeros = function(n, total_digits)

                n = n.toString();

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

            ;

 

        )(jQuery);

 

        $(document).ready(function()

 

            // Initialize the counter

            var counter = 0;

 

            $('#fields-button').click(function()

 

                // Increment and pad the counter

                var padded_counter = $.leading_zeros(++counter, 3);

 

                // Create the new field

                var extrafield = '<tr><td>List Item ' + padded_counter + '</td><td>';

                extrafield += '<input type="text" name="' + padded_counter + '"></td></tr>';

 

                // Add the new field to the table

                $('#fields').append(extrafield);

            );

        );

 

    </script>

</head>

<body>

    <button id="fields-button">Add Field</button>

    <form action="some_script.pl" method="get">

    <table id="fields"></table>

</form>

</body>

</html>

```

This code allows you to dynamically add fields to a table, incrementing the counter and padding the numbers with leading zeros.


Heard It Again: A Closer Look

Posted on Thu 16 December 2021 in Economics • Tagged with rants

Once again, I came across the statement: "The U.S. has 4% of the world’s population and consumes 25% of the world’s power." This time, it was on the NBC Evening news, and as usual, the reporter didn't delve into the reasoning behind this comparison. What could these two seemingly unrelated facts possibly have in common?

 

At first glance, this statement might appear to carry some weight. How could only 4% of the world's population be responsible for a quarter of global power consumption? To make sense of this, we should consider production as a crucial factor.

 

Gross Domestic Product (GDP) is one of the best measures for comparing countries or populations. According to the International Monetary Fund, the global GDP in 2006 amounted to $48,245,198,000,000, while the U.S. GDP was $13,194,700,000,000. Interestingly, the U.S. GDP represents approximately 27% of the world's GDP, closely aligning with the 25% figure for U.S. power consumption in relation to the world's total.

 

This coincidence suggests that the U.S. power consumption isn't necessarily disproportionate when considering its economic output in the global context. So, while the statistic may sound striking at first, a deeper examination reveals a more reasonable correlation between power consumption and economic activity on a global scale.


Botkin on Nature, the Environment, and Global Warming: Insights from Daniel Botkin

Posted on Wed 08 December 2021 in The Good Fight • Tagged with economics

On the November 26, 2007, edition of the EconTalk podcast, Daniel Botkin shared some fascinating insights about nature and its relationship with change.

 

Botkin highlighted a crucial aspect: most species have evolved and adapted to change over time. They rely on change for their survival and well-being. The assumption of a steady state, where everything remains constant, goes against the very needs of these species.

 

His observation extends beyond climate change. For instance, in certain forests, the vegetation has evolved to withstand and even thrive after wildfires. When we interfere by preventing natural fires from playing their role in the wilderness, we unwittingly disrupt the balance of nature. Botkin's point is that our perception of what nature should be often influences our actions towards it, sometimes with detrimental consequences.

 

The EconTalk podcast series, featuring Russ Roberts and a variety of expert guests, covers diverse topics in economics. Many of these guests are economists specializing in specific fields. These hour-long podcasts offer a valuable opportunity to delve into economic discussions, so consider setting aside some time to explore the world of economics through their engaging conversations.


Consumer Protection: Balancing Regulation and Responsibility

Posted on Wed 08 December 2021 in The Good Fight • Tagged with economics

In a recent political discussion about libertarianism, an interesting argument emerged, shedding light on the delicate balance between consumer protection and individual responsibility.

 

The scenario presented involved a laptop spontaneously catching fire, resulting in the loss of a year's worth of work product. The consumer, in this case, was promised a mere $1000 to replace the laptop. Seeking legal recourse, they discovered that pursuing a claim for the lost work product could cost around $35,000 and take up to five years. This situation raised a critical question: should regulations be in place to safeguard consumers in such instances?

 

One perspective argued that the consumer in question had acted recklessly by storing millions of dollars' worth of valuable information on a single device without any backups. Regardless of the laptop's battery quality, the risk of losing such invaluable data was far too great. Responsible data management includes immediate backups, which can be effortlessly facilitated by today's wireless technology, thereby mitigating the risk.

 

The counterargument emphasized that no regulation could have entirely protected this particular consumer. Various unforeseen circumstances, such as hard drive crashes, theft, or accidents, could have resulted in the same loss of data. Therefore, imposing excessive regulations to absolve individuals of the need to exercise data consciousness would be an inefficient allocation of resources.

 

This discussion underscores the importance of finding a balance between consumer protection measures and personal responsibility. While regulations play a role in ensuring fair treatment and safety, individuals also bear a responsibility to safeguard their interests, particularly in an increasingly digital and interconnected world.


Consumer Protection: Balancing Regulation and Responsibility

Posted on Mon 06 December 2021 in The Good Fight • Tagged with energy, motion, politics, rants

In a recent political discussion about libertarianism, an interesting argument emerged, shedding light on the delicate balance between consumer protection and individual responsibility.

 

The scenario presented involved a laptop spontaneously catching fire, resulting in the loss of a year's worth of work product. The consumer, in this case, was promised a mere $1000 to replace the laptop. Seeking legal recourse, they discovered that pursuing a claim for the lost work product could cost around $35,000 and take up to five years. This situation raised a critical question: should regulations be in place to safeguard consumers in such instances?

 

One perspective argued that the consumer in question had acted recklessly by storing millions of dollars' worth of valuable information on a single device without any backups. Regardless of the laptop's battery quality, the risk of losing such invaluable data was far too great. Responsible data management includes immediate backups, which can be effortlessly facilitated by today's wireless technology, thereby mitigating the risk.

 

The counterargument emphasized that no regulation could have entirely protected this particular consumer. Various unforeseen circumstances, such as hard drive crashes, theft, or accidents, could have resulted in the same loss of data. Therefore, imposing excessive regulations to absolve individuals of the need to exercise data consciousness would be an inefficient allocation of resources.

 

This discussion underscores the importance of finding a balance between consumer protection measures and personal responsibility. While regulations play a role in ensuring fair treatment and safety, individuals also bear a responsibility to safeguard their interests, particularly in an increasingly digital and interconnected world.