checkboxes selection using JavaScript

Can someone help troubleshoot my JavaScript code for creating multiple checkboxes? It seems that all the boxes are being checked at once and I'm not sure why.

for(var i=0; i<3; i++){
    document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText();' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
}

var item_box = document.getElementsByName('myItem');
var x;
//alert(item_box.length);
function changeText(){
  for(x=0;x<item_box.length;x++){
   if(item_box[x].hasAttribute('checked')){
    item_box[x].value="0";
    item_box[x].setAttribute('checked', true);
    item_box[x].removeAttribute('checked');
    item_box[x].setAttribute('disabled', false);
   } else {
    item_box[x].value="1";
    item_box[x].setAttribute('checked', false);
    item_box[x].setAttribute('disabled', true);
    item_box[x].removeAttribute('disabled');
   }
  }
}

Answer №1

    for(let x=0; x<3; x++){
        document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText(this,"+x+");' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
    }
    
    var item_box = document.getElementsByName('myItem');
    
    function changeText(e,x){
        item_box[x].value = e.checked ? 1 : 0;
        item_box[x].disabled = !e.checked;
    }

Answer №2

If you only want one input box to be enabled, use the code snippet below:

for(var i=0; i<3; i++){
    document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText(this);' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
}


function changeText(element){
   var inputBox = element.parentElement.parentElement.nextSibling;
    
   if(inputBox.hasAttribute('checked')){
    inputBox.value="0";
    inputBox.setAttribute('checked', true);
    inputBox.removeAttribute('checked');
    inputBox.setAttribute('disabled', false);
   } else {
    inputBox.value="1";
    inputBox.setAttribute('checked', false);
    inputBox.setAttribute('disabled', true);
    inputBox.removeAttribute('disabled');
   }
}

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

Discovering the total count of pointers within an array of pointers

Is it possible to determine the length or number of pointers in an array of pointers? For example: class Notifications { iMessage **messages; public: Notifications(); Notifications(const Notifications&); Notifications& operator ...

Regular expression: Identify all instances of double quotes within a given string and insert a comma

Is there a way to transform a string similar to the following: ' query: "help me" distance: "25" count: "50" ' Into either a JavaScript object or a JSON string that resembles this: '{ query: "help me", distance: "25", count: "50" }' ...

Angular JS Sliding Navigation Bar

Embarking on my initial endeavor with AngularJS, I am eager to implement a tree structure within a flyout menu. After stumbling upon this dropdown menu demonstration at , I am inspired to modify it into a sleek Flyout menu. In the referenced example, chil ...

Ways to prevent browser scrolling on smartphones and tablets

Having a simple HTML file with an iframe embedded, I have been attempting to prevent my browser from scrolling in both documents. However, this solution works intermittently and does not provide consistent results. I have tried applying various event list ...

What is the best way to make buttons trigger an action on a jQuery confirmation dialog?

Clicking on an image within the jQuery Dialog will open a confirmation dialog box prompting you to confirm if you want to delete. You can choose between Yes or No for confirmation. This functionality is implemented using three files: The main file index. ...

Is the popup successfully closed when the button is tested?

I am currently working on testing a simple pop-up to see if the clicked button closes the popup using testing-library/react. The approach in the documentation doesn't seem to be working for me, as I can successfully console log the button but fireEven ...

The unveiling of Numpy's "object" data types

Looking for suggestions on how to efficiently unwrap a numpy array with dtype=object using Python. Consider the following example: array([array([ 1, 2, 3]), array([ 4, 5, 6]), array([ 7])], dtype=object) The desired output is: array([ 1, ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

Insert content to the center of a document according to a specific array

I need to insert text into the center of a document if a specific word from an array is found: array:[hello,goodbye] It is important that find and replace is not used. An example sentence from file.txt: Hello there, goodbye then. New Sentence: Hello ...

How come my jQuery ajax request is successful but the $_POST array remains empty?

Here is my first query on this forum, please be patient with me: The code snippet for my ajax request is: <script> $.ajax({ type:"POST", url:"http://localhost/folder/something.php", data: { BuildingName:'Jacaranda'}, success: function(da ...

Creating Docker images in a lerna monorepo without the need for publishing

In the context of Lerna monorepos, the primary goal is to facilitate branch building and deployments. The challenge arises from the fact that Lerna monorepos either consolidate dependencies in NPM or utilize yarn workspaces to achieve the same outcome, re ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Retrieve the information from a fetch call and save it for later use

Greetings to the wonderful StackOverFlow community. As a beginner in web development, I have countless questions swirling in my mind. The focal point of my query is regarding a fetch request in JavaScript. I am struggling to extract the data (userId) fr ...

View in Laravel 5.2 showcasing three distinct tables

Hey there, I'm struggling to showcase three different tables in one view using Laravel 5.2. Despite my efforts, I can't seem to get it right. This is what my HomeController.php looks like: namespace App\Http\Controllers; use Illumina ...

What is the reason behind lightbox not disabling scrolling?

While using the default lightbox2 CSS and JavaScript, everything is functioning correctly except for an issue on Safari mobile. When I click an image and the lightbox opens, swiping to the left reveals blank white space despite having overflow-x set to hid ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Detecting collisions in Three.js

I seem to be overlooking something quite fundamental, as I can't seem to find a solution in the documentation or any other working code examples. I am currently creating a basic museum using THREE.js libraries. While most of it is set up, I need to im ...

What is the reason for me continuously receiving the error "cannot read map of undefined"?

Having trouble debugging my redux sagas and react integration. No matter what initial state I set, I keep running into undefined errors when trying to map through the data. I've tried null, undefined, and empty arrays but nothing seems to work. Can a ...