The quickest method to iterate through numerous form elements efficiently in JavaScript

I am currently dealing with looping through a large number of javascript elements, including checkboxes and select elements. The objective is to toggle the checkboxes between checked and unchecked states, and to enable or disable the select elements based on whether a main checkbox is checked.

 <script>
 function processFormElements(start, end, isChecked) {
    for (var i=start; i < end; i++) {
        document.getElementById('chkbox_'+i).checked = isChecked;
        document.getElementById('select_'+i).disabled = !(isChecked);
    }
}
</script>

 Check this: <input onchange='processFormElements(0,10000,this.checked);' type='checkbox'  value = '0'><br/><br/>

 <?php
 for ($i=0; $i < 10000; $i++) {
     echo "Check: <input type='checkbox' id='chkbox_$i' value = '1'> ";
     echo "Select: <select disabled='disabled'  id='select_$i'><option selected>1<option>xyz</select><br/>";
 }
 ?>

The current implementation achieves the desired functionality but it appears to be processing slowly through the form elements, causing noticeable lag. Are there any optimization techniques that can be applied to improve the performance?

Answer ā„–1

In the scenario where your checkboxes and select boxes are positioned right after each other, consider utilizing nextElementSibling. The issue lies in the fact that document.getElementById has to sift through all elements in the DOM tree to locate the one with the corresponding ID (although there may be optimizations like hash tables for quicker ID lookup).

By using nextElementSibling, you can navigate through elements akin to traversing a tree structure, thereby reducing search time.

For instance:

var cb = document.getElementById('chkbox_' + min),
    sb = document.getElementById('select_' + min);
while (cb !== null && sb !== null) {
    cb.checked = isChecked;
    sb.disabled = !isChecked;

    cb = cb.nextElementSibling;
    sb = sb.nextElementSibling;
}

UPDATE:

As pointed out by David below, not all browsers offer support for nextElementSibling. A workaround is to use nextSibling.

Instead of:

cb = cb.nextElementSibling;

Try this:

while(cb !== null && cb.nodeName != 'Element') { cb = cb.nextSibling; }

However, it's worth noting that the number of browsers lacking support for nextElementSibling is diminishing steadily, and the nextSibling alternative comes with its set of challenges. Whether or not to cater to older browser versions depends on your discretion (or possibly your superior's decision).

Answer ā„–2

Utilizing Jquery in this scenario would likely yield better results:

$(':checkbox').each(function () {  
    this.checked = isChecked; 
});
//isChecked-true/false

Hopefully, this approach will result in the desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to pass data from a radio button without it showing up in the URL?

I have an interesting challenge ahead where I need to demonstrate a proof of concept. This involves: Transferring data from one page to another using the URL section and then displaying that passed data on a different page. Transferring data from one ...

Concealing the presence of jquery and javascript

Currently developing a model-view-controller application (but this question can apply to any website). I'm contemplating whether it's acceptable to have exposed jQuery and JavaScript in a view. Essentially, when the program is run and source code ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...

Rendering JSON maps from MongoDB using Node.js

I am looking to display data from a JSON map in my Express application Here is my code: var b = det.map(function(h) { var soalid = h.id_soal; var idarray = [ ]; for (var i = 0; i < soalid.length; i++) { Soal.findOne({ ...

Force restart broken socket within Node.js program using Socket.IO programmatically

I have a simple one-to-one client and server Node.js based application. The Node.js is running on Linux (Intel Edison). I am attempting to automatically reboot the Linux server whenever the socket connection is broken. Is this achievable? Below is my unco ...

Choosing various buttons using jQuery

I'm trying to create a feature where I have a list of items with buttons next to each one. When a button is clicked, I want the corresponding item to be displayed in another section on the page. The challenge Iā€™m facing is figuring out how to estab ...

Load jQuery to display the Bootstrap modal.ORUse jQuery to load and

My attempt to use the .load() function to display a bootstrap modal immediately on my page isn't working. The modal opens but cannot be closed afterward. The goal is to load a list of players in a modal whenever a team name with the class .team is cl ...

The initialization of the R Shiny HTML canvas does not occur until the page is resized

I am currently facing an issue while integrating an HTML page with a canvas into my shiny R application using includeHTML(). The packages I am using are shiny, shinydashboard, shinycssloaders, dplyr, and DT. Everything is working perfectly fine except for ...

Tips for avoiding the Basic Authentication popup

I am working on a Java application using JSF that requires JavaScript to connect to a website with Basic authentication. My goal is to replicate the experience of manually entering a username and password in the popup form. Despite trying various methods ...

Tips on implementing two ng-repeat directives within a specific element

Inside a JSON file, there is an array that needs to be iterated within <td> tags. The functionality entails creating a table based on user input, which includes the number of rows, input columns, and output columns provided by the user. Three arrays ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

Customizing the background color of rows in Node.js XLSX using the npm package

I am currently working on a project that involves reading an Excel sheet and then coloring specific rows based on backend data. While I have successfully been able to read the sheet and create a new one with updated information, I am facing issues when try ...

php$insert new field into mysql table using form insertcell

How do I insert a column in MySQL? I am struggling with the insertCell form. I have tried but I can't seem to add a MySQL column using my JavaScript code with PHP. I am familiar with Php PDO, but this seems difficult to me. Can someone guide me on ho ...

Having issues with setTimeout on Chrome for Android when the browser is out of focus. Any ideas for resolving this?

I developed a web application that functions as a messaging system, where users can submit messages and others can receive them. The system operates through AJAX, with the front end using JavaScript to interact with a PHP backend. Everything runs smoothly ...

Establishing the Access-Control-Allow-Origin

I have a basic .NET web service: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http ...

deleting an object from an array in JavaScript

I have a collection of objects that looks like this: [{ "id": 2, "price": 2000, "name": "Mr Robot T1", "image": "http://placehold.it/270x335" }, { "id": 1, "price": 1000, "name": "Mr Robot T2", "image": "http://placehold.it ...

Angular, a Self-sufficient Module of Cascading Style Sheets

I have developed a factory that generates HTML content. I want to showcase this generated HTML within a specific section of my application, without its CSS affecting the rest of the site, and vice versa. While using an iframe is one option, I believe there ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

Jasmine's unexpected outcome in array comparison

I am currently experimenting with this code: describe("array item removal", function () { it("creates a gap in the array", function () { var array = ['one','two','three']; delete array[1]; //'two&apos ...

Using express.js to send multiple post requests to the same url

My website features a login form where users input their information. Upon submission, a post request is made to check the validity of the provided information. If successful, users are redirected back to the login form where they must enter the code sent ...