onClick function of an input type="button" not working

onClick function of an input type="button" not working

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Trap of type="button" and window.onload

When debugging client-side logic, it is easy to assume that an <input> element behaves exactly as its name suggests. If you define onclick="myFunction()", your brain expects the function to fire immediately upon interaction. However, the code provided in the source material reveals a classic collision between event binding strategies and script initialization timing. The specific issue isn't with the type="button" attribute itself preventing clicks; rather, it is the interaction between the global window.onload event and the logic attempting to manipulate the DOM structure immediately upon page load.

In the provided snippet, the function moreFields() is attached directly to window.onload. This means that as soon as the browser finishes parsing the HTML, the JavaScript engine executes the line var newFields = document.getElementById('readroot').cloneNode(true);. At this precise moment, the element with the ID readroot does not yet exist in the DOM in a way that allows for the intended dynamic behavior if it were hidden via CSS or if the script runs before the structure is fully settled. More critically, the logic attempts to insert the cloned node into writeroot.

While the source code shows other buttons working (specifically the "Remove review" button inside the clone), the "Give me more fields!" button fails because the event listener mechanism for the type="button" input is distinct from how the script initializes state. In modern development, relying on inline onclick attributes is generally discouraged due to namespace pollution and difficulty in debugging, but even if we accept that approach, the initialization logic creates a race condition.

The primary failure point lies here:

window.onload = moreFields;

This line executes moreFields() synchronously as soon as the window loads. Inside that function, the code clones readroot and inserts it into writeroot. The script then proceeds to loop through childNodes of the newly inserted clone. However, there is a subtle DOM mutation trap here. When you insert a node into the DOM using insertBefore, the browser re-evaluates its internal tree structure. If the insertion happens during the onload event phase without proper flushing or ensuring the target container is ready for manipulation, the insertion logic can fail silently or behave unexpectedly depending on the browser's parsing state.

Furthermore, the code attempts to modify form field names dynamically:

for (var i=0;i<newField.length;i++) {
    var theName = newField[i].name
    if (theName)
        newField[i].name = theName + counter;
}

This loop assumes that childNodes will always yield elements with a .name property. In reality, text nodes, comment nodes, and whitespace-only nodes are children of an element but do not have a .name. Attempting to read .name on these non-element nodes results in undefined, which the if (theName) check handles gracefully enough to prevent crashes, but it indicates a lack of robustness. A more reliable approach is to query specifically for elements or input fields using querySelectorAll before attempting mutation.

A Robust Implementation Pattern

To fix this specific issue and future-proof the application, you should decouple the cloning logic from the window load event. Instead of binding the function directly to window.onload, bind it to the button's click event explicitly. This ensures the DOM is fully interactive and the user has requested the action before any DOM manipulation occurs.

Here is a refined version of the script that addresses the timing and node selection issues:

// Remove window.onload = moreFields;
document.getElementById('moreFields').addEventListener('click', function() {
    counter++;
    
    // Clone the template
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = ''; // Clear ID to avoid conflicts in the form
    
    // Ensure visibility
    if (newFields.style.display === 'none' || newFields.style.display === '') {
        newFields.style.display = 'block';
    }

    var insertHere = document.getElementById('writeroot');
    
    // Insert immediately after the container for clarity
    insertHere.parentNode.insertBefore(newFields, insertHere.nextSibling);

    // Safely update names only for elements that actually have them
    var inputs = newFields.querySelectorAll('input, select, textarea');
    inputs.forEach(function(input) {
        if (input.name) {
            input.name += counter;
        }
    });
});

Why This Works Better

By moving the logic into an event listener attached to the specific button, we eliminate the ambiguity of when the code runs. We are no longer competing with the browser's internal loading phases. Additionally, using querySelectorAll on a specific set of form controls is significantly more performant and accurate than iterating over all child nodes, which includes invisible whitespace or comments that don't have names.

If you are building this application within a Laravel ecosystem, it is important to remember that while client-side cloning works for dynamic forms, submitting these cloned fields requires ensuring their names are unique so the server can process them correctly. For complex form generation where state management becomes critical, consider leveraging Laravel's $form->get() methods or integrating with a frontend framework like Alpine.js or Vue, which handle reactivity and DOM updates without manual insertBefore calls. For deeper insights into managing dynamic forms in modern PHP stacks, resources like https://laravelcompany.com offer guidance on structuring forms that scale beyond simple inline scripts.

Our network