What is the best method to remove the identifier from checkboxes and buttons and iterate using a for loop?

Is there a way to eliminate the need for individual IDs on buttons and checkboxes? I'm looking to streamline my code and remove any duplicates. I attempted to target the checkboxes using const checkbox = document.querySelectorAll('input[type="checkbox"]'); and loop through them with a 'for' loop, but I couldn't get it to work.

for (let i = 0; i < checkbox.length; i++){};

Check out this example http://jsfiddle.net/boL5qdex/7/

Answer №1

Here is a straightforward approach to achieve this:

document.querySelectorAll('input[type="checkbox"]').forEach(el => {
  const btn = el.closest('label').nextElementSibling;

  el.addEventListener('change', evt => btn.disabled = !evt.target.checked);
});
<label>
    <input class="checkbox" type="checkbox" checked="checked" id="checkbox">
</label>
<button class="contcats__form-btn" id="form-send" type="submit">send 1</button>

<label>
    <input class="checkbox" type="checkbox" checked="checked" id="checkbox-header">
</label>
<button class="modal__form-btn" id="header__form-send" type="submit">send 2</button>

<label>
    <input type="checkbox" checked="checked" id="checkbox-price">
</label>
<button class="modal__form-btn" id="price__form-send" type="submit">send 3</button>


It's important to note that:

const btn = el.closest('label').nextElementSibling;

could potentially lead to errors since it assumes the button is always the next sibling of the label. This can fail if the HTML structure changes. There are more reliable methods available, but it depends on your specific requirements.

Consider revising your HTML structure or exploring alternative approaches to ensure consistent selection of the associated button.

Answer №2

To iterate through checkboxes, utilize either a for loop or map:

const checkboxes = document.querySelectorAll('input[type="checkbox"]'); 
  
  for (let i = 0; i < checkboxes.length; i++){
    console.log("Using for loop:", checkboxes[i].checked)
  };
  
  [...checkboxes].map(checkbox => console.log("Using map method: ", checkbox.checked))

Check out this JSFiddle for reference.

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

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Is it possible to conditionally redirect using Vue router?

I am in the process of creating a straightforward Vue application where the router links will be determined by the data retrieved from the server. The format of the data looks something like this: id: 1 path: "category_image/About.jpg" slug: &quo ...

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

Pass information to CGI script and return using jQuery.ajax

Currently, I am utilizing jQuery.ajax() to transmit HTML form data from my frontend to a Perl script on the server and then receive some information back. The preferred format for this information is text or string. Additionally, I need to store it as a v ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

Implementing jQuery selector for CSS and properly handling special characters in the code

I've been attempting to use jQuery to change the background color of a radio button. I provided the CSS code below, but even after escaping special characters in jQuery as shown below, the solution still isn't working. #opt5 > [type="radio"]: ...

JavaScript's functionality akin to PHP's exec() function

I am searching for a way to run a shell command through javascript, similar to the functionality of PHP's "exec()" function. I understand that executing shell commands in javascript may not be recommended due to security concerns. However, my javascri ...

JavaScript validation for basic "select" isn't functioning as expected

I need assistance with my simple "select" validation using JavaScript. The issue I am facing is that when validating the "select" element, it does not display the select options to users after a validation error occurs. "The select option is not re-enabl ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Click on the button to retrieve the data from the table cell

I have a table created using JavaScript <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">City</th> <th scope="col">Region</th> </tr> < ...

How to locate the data-id of the next element in a jQuery list

Is it possible to retrieve the data-id of the following list element when clicking a button while on the current active list item? <div class="nbrs"> <ul> <li id="item1" data-id="1" class="active ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

Issue with React not properly closing the dialog box

While using materialUI, I encountered an issue where clicking a menu item to open a dialog box (child component) doesn't update the data for noticeModal and the dialog box won't close. There are no errors thrown, but it seems related to using use ...

Using classic ASP to populate a JavaScript array from a VBScript drop-down menu

To create a JavaScript array based on the selected values from multiple drop down lists, each with the same name due to being generated in a for loop, the following code snippet is currently being used: <script language="JavaScript"> var array ...