Scan webpage for checkbox elements using JavaScript

When my page loads, dynamic checkboxes are generated using the following HTML:

<input type='checkbox' name='quicklinkscb' id='quicklinkscb_XX'/>

The XX in the ID represents the unique identifier of an item from the database.

My goal is to use JavaScript to parse the page and perform the following actions for each checkbox:

1. Extract the ID by removing 'quicklinksscb_'

if(checkbox is checked)
{
  add to add list
}
else
{
  add to remove list
}

I need to accomplish this purely on the client side without using a checkbox list. Any insights or guidance would be greatly appreciated.

Answer №1

When iterating through form elements in vanilla JavaScript:
<pre><code>$(':checkbox').each(function() {
    var tag = $(this).attr('id');
    tag.replace(/^quicklinkscb_/, '');
    if($(this).attr('checked'))
        add_to_add_list(tag);
    else
        add_to_remove_list(tag);
});

Answer №2

Although I acknowledge that the jQuery code snippet presented by chaos is more concise and easier to understand compared to the POJ sample, I do have to question the necessity of utilizing the large jQuery library for this specific task.

Following aditya's advice, here is how my POJ version would look:

var 
  add_list = [],
  del_list = [];

for (var inputs = document.getElementsByTagName ('input'), cb, i = inputs.length;
     i--;)
  if ((cb = inputs[i]).type === 'checkbox') {
    cb.id = cb.id.replace (/^quicklinkscb_/, '');
    (cb.checked ? add_list : del_list).push (cb);
  }

In understanding the original query as requesting a modification of checkbox ids alongside the addition or removal of elements from lists, an alternative implementation similar to chaos's approach would be:

for (var inputs = document.getElementsByTagName ('input'), cb, i = inputs.length;
         i--;)
  if ((cb = inputs[i]).type === 'checkbox')
    (cb.checked ? add_list : del_list).push (cb.id.replace ((/^quicklinkscb_/, '')));

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

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Transforming a Blob document into JSON format

I am attempting to convert a blob file into JSON format in order to transmit it via AJAX requests. Despite my efforts with the code below, I have not been successful in achieving this task. When I attempt to parse the JSONified file, I end up with a comp ...

Angular 4 is in need of CORS support

I have a server application with CORS enabled, which works well with my AngularJS client (1.x). However, I am now upgrading to Angular 4 and encountering the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the rem ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

Tips on concealing the prior row through ajax

Whenever I click on the first row of the left table, the output appears on the right side. However, when I click on the second row of the first table, only the output for the second row should be displayed. Unfortunately, both the outputs for the first and ...

When it is first activated, the Ajax .load() function will not function correctly

I recently encountered an issue with a tab system that I implemented using the .load function to load content dynamically. The problem arose because the page containing this tab system was loaded via ajax, causing the initial call to the tab function to di ...

determining the file size of images being loaded remotely by retrieving their image URLs

There is a straightforward regex function in jQuery that I'm using to automatically add an image tag to image URLs shared by users. This means that when a user posts something like www.example.com/image.jpg, the image tag will be included so that user ...

The function is continuously executed using the setInterval method, each time with distinct parameters

Hey there, I have a question about a function that opens a chat form with different attributes when given an emp_id parameter. My goal is to have this form automatically refresh every 10 seconds. However, the current implementation is causing some issues. ...

Guide to creating a clean and minimalistic tabbed menu using CSS

Looking for CSS code for the tabbed menu shown above. I've tried several options but haven't been able to achieve the exact design I want. Here is the directive, HTML, and CSS code provided: <div id="tabs"> <ul> <li> ...

The function JSON.parse(obj) is malfunctioning and throwing an error, but an online parser is displaying the data correctly

Currently, I am in the process of developing a chatApp for my portfolio. I am working with technologies such as Flask on the back-end and vanilla on the front-end to gain a better understanding of how everything works. My main goal is to display events bas ...

Is it possible to export multiple named exports in a single set without changing how variables are called?

In my constants file I have: export const CONSTANT1 = 'CONSTANT1'; export const CONSTANT2 = 'CONSTANT2'; export const CONSTANT3 = 'CONSTANT3'; export const CONSTANT4 = 'CONSTANT4'; export const CONSTANT5 = 'CONS ...

"Learn how to dynamically update the user interface in express.js using handlebars without having to refresh the

As a newcomer to using express.js and Handlebars, I am faced with the challenge of implementing autocomplete functionality. Specifically, I want to enable autocompletion in a text input field without triggering a page refresh when users interact with it. C ...

Context Provider executing SetInterval twice

For some reason, the below code in global.js is running twice when I run my react app, but I can't figure out why. I have used setInterval to test, and the intervals are always running two times. Perhaps I am not initializing correctly. Even after rem ...

Jquery's $.parseJSON function faces a critical error

In my code, I have a simple markup generated through AJAX on the server. The relevant line is the following: <div id='login_history_resp' class='paginator_slider' DATA-params="{'SLIDER_LEFT_POS':139, ...

Having trouble with the babel-loader and its version compatibility, as well as not finding the babel-loader folder in the node_modules directory when

Here are the steps I've taken: I cloned the project from Github. Ran the command 'yarn' to start the project. Encountered an error after running the command 'yarn start'. Even after following the steps provided in the e ...

What measures can be taken to avoid RowIDs resetting in jqGrid?

After each pagination action (such as increasing the number of rows or moving to the next page), I noticed that the rowIDs get reset for some reason. For example, let's say I have a total of 75 records. I am displaying 15 records per page, resulting ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

Inexperienced individual asks: 'Is it possible to accomplish this task using Dojo and Ajax?'

On my website, there is a feature that sends an initial request to a web service. Once this request is sent, the user has to wait for a specific amount of time before being able to send a second request. During this waiting period, I would like a countdo ...

Using v-model in Vue with jQuery integration

I wrote a jQuery code that is executed when the mounted hook runs mounted() { this.$progress.finish(); var geocoder = new google.maps.Geocoder(); var marker = null; var map = null; function initialize() { var $latitude = document.getEl ...