Inspect all checkboxes created by JavaScript

I'm attempting to develop a checkall checkbox that will automatically select all the checkboxes I've created using JavaScript.

Firstly, I gather the number of rows and columns from the user and then use JavaScript to generate a table and insert checkboxes into those cells.

Now, my goal is to implement a checkall checkbox that will check all the dynamically generated checkboxes through JavaScript.

Below is the code snippet where I'm generating the cells and checkboxes...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>


<script type="text/javascript">

  function createTable() {
      // alert("invoked")
     var a, b, tableElem, rowElem, colElem, check,inc,hall,theatre,row,col;

     a = document.getElementById('rows').value;
     b = document.getElementById('cols').value;

     hall =  document.getElementById('theatreName').value;
     theatre =  document.getElementById('hallID').value;

     document.getElementById('hdnhallName').value = hall;
     document.getElementById('hdntheatreName').value = theatre;
     document.getElementById("norow").value = a;
     document.getElementById("nocol").value = b;
     //alert(document.getElementById('hdntheatreName').value);
     //alert(document.getElementById('hdnhallName').value);

     inc=1;

     if (a == "" || b == "") {
        alert("Please enter some numeric value");
     } else {
        tableElem = document.createElement('table');
        tableElem.style.border="1px solid black";


           for (var i = 0; i < a; i++) {
               rowElem = document.createElement('tr');

               for (var j = 0; j < b; j++) {
                 colElem = document.createElement('td');
                 colElem.style.border="1px solid black";
                 colElem.appendChild(document.createTextNode(inc)); //to print cell number
                 rowElem.appendChild(colElem);
                 check = document.createElement('input');
                 check.type = "checkbox";
                 check.name = "chkSeat";
                //check.value = "chk"+inc;

                 check.value = inc;
                 check.id = "chk"+inc;
                //alert(check.value);


                 colElem.appendChild(check);
                 inc++;
               //colElem.appendChild(lab);

        }

        tableElem.appendChild(rowElem);
    }


            document.getElementById("seat_tble2_td").appendChild(tableElem);
            document.getElementById("sub_seat").disabled = false;
            document.getElementById("chkall").disabled=false;



}



}


 function checkall(bx){

           var checkboxes = document.getElementsByName('chkSeat');
           for (var i = 0; i < checkboxes.length; i++)
              checkboxes[i].checked = source.checked;



}



</script>
    <h1>Create seating plan</h1>
    <table id="table_seat" border="1" width="500" >
        <tr>
           <td>
              <!-- <form action="" name="f1" onsubmit=""> -->
               <table width="100%" border="0" cellpadding="5" cellspacing="0">
                 <tr>
                    <td width="40%" height="40" class="txt">Theatre Name: </td>
                    <td width="60%"><input type="text" name="theatreName" id="theatreName"/></td>
                 </tr>
                 <tr>
                    <td height="46" class="txt">Hall ID : </td>
                    <td><input type="text" name="hallID" id="hallID"/></td>
                </tr>
                <tr>
                    <td height="46" class="txt">Rows : </td>
                    <td><input type="text" name="rows" id="rows"/></td>
                </tr>
                 <tr>
                    <td height="46" class="txt">Columns : </td>
                    <td><input type="text" name="cols" id="cols"/></td>
                </tr>
                <tr>
                    <td align="right"> <input type="submit" name="Submit" value="Generate seat plan" onclick="createTable();"/></td>
                    <!--<td align="right"> <button style="width:20px; height:10px;" onclick="createTable();"></button></td>-->
                    <td valign="top" align="left"><input type="reset" name="Submit2" value="      Reset      " /></td>


                </tr>

             </table>
           <!--  </form> -->

           </td>
       </tr>

   </table>
    <form action="SeatMap" method="post" name="f1" onsubmit="">
        <table id="seat_table2" cellpadding="10">
                   <tr>

                       <td id="seat_tble2_td">




                       </td>

                   </tr>




                    <tr>

                       <td id="seat_tble2_td1">

                           <input type="hidden" name="hdntheatreName" id="hdntheatreName"/>
                           <input type="hidden" name="hdnhallName" id="hdnhallName"/>
                           <input type="hidden" name="norow" id="norow"/>
                           <input type="hidden" name="nocol" id="nocol"/>
                           <input type="submit" value="Submit" id="sub_seat" name="sub_seat" disabled>


                       </td>

                   </tr>


                   <tr>

                       <td>

                           <input id="chkall" type="checkbox" name="chkall"  onClick="checkAll(this);" disabled />Check All

                       </td>
                   </tr>


  </table>
 </form>
</body>

The JavaScript function I tried creating for checkall doesn't seem to be functioning properly. Any assistance would be greatly appreciated. I am working with JSP and Servlets for server-side coding while utilizing JavaScript or potentially jQuery on the client side.

Answer №1

Although this question has already been addressed, I would like to share how I tackled it...

Situation: In my case, the data rows are generated from a database using PHP. As these rows are displayed in a table format on the screen, I decided to include a textbox alongside each row with a counter. For example, the name of the first checkbox would be: chkCheckbox_$Count, where the count variable increments for every new row.

This is how my HTML structure was implemented:

<input type="checkbox" name="chkCheckbox_All" onclick="CheckAllCheckboxes();" />Check All
<?php
$Count = 1;
while($Field = mysql_fetch_array($Result))
    {
    ?>
    <tr>
        <td>
            <input type="checkbox" name="chkCheckbox_<?php echo $Count; ?>" />
        </td>
        <td><?php echo $Field['ProductID']; ?></td>
        <td><?php echo $Field['ProductName']; ?></td>
        <td><?php echo $Field['ProductDescription']; ?></td>
        <td><?php echo $Field['Quantity']; ?></td>
        <td><?php echo $Field['Price']; ?></td>
        <td><?php echo $Field['Discount']; ?></td>
    </tr>
    <?php
    $Count++;
    }
    ?>
    <input type="hidden" id="txtUltimateRowCount" value="<?php echo $Count-1; ?>" />

Furthermore, here is the Javascript function used:

<script>
function CheckAllCheckboxes() {
    var Count=1;
    var EndValue=document.getElementById('txtUltimateRowCount').value;
    if (document.getElementById('chkCheckbox_All').checked == true)
        {//Checked so Check All.
            while (Count <= EndValue)
                {
                document.getElementById('chkCheckbox_' + Count).setAttribute('checked', 'checked');
                Count=Count+1;
                }
        }
    else if (document.getElementById('chkCheckbox_All').checked == false)
        {//Unchecked so Uncheck All.
            while (Count <= EndValue)
                {
                document.getElementById('chkCheckbox_' + Count).removeAttribute('checked');
                Count=Count+1;
                }
        }
}
</script>

Answer №2

Include this checkbox in the header of the table

<input type="checkbox" onclick="$('input[name*=\'selected\']').attr('checked', this.checked);" />

and label all checkboxes in the body as

<input type="checkbox" name="selected" />
<input type="checkbox" name="selected" />
<input type="checkbox" name="selected" />

............

this method should function properly

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 turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data. The standard approach would be: this.resultData = response.data.results this.totalResults = response.data.total this.perPageResults = response.data.per_page However, ...

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

Discover the simple steps to generating dynamic variables with jQuery!

I am looking to dynamically create jQuery variables based on values in a loop. Here is an example of what I am trying to achieve. array=["student","parent","employee"] $.each(user_types, function( index, value ){ var dynamicType = value + "_type"; // t ...

Spinner loading - stays centered on screen even when scrolling up or down

<div id="Dvloading" style="float: left;"> <i id="loadingSpinner" class="icon-spinner icon-spin blue" style="margin-left: 50%; position:absolute ; margin-top: 25%; z-index: 1000; font-size: 800%;"></i> </div> This code displ ...

Simple request results in an error

I have been experimenting with the Electrolyte dependency injection library, but I am encountering an error even when trying a simple script that requires it. I haven't come across any discussions or problems similar to mine in relation to this issue ...

Selenium Assistance: I'm encountering a scenario where on a webpage, two elements share the same Xpath, making it difficult to differentiate them based on even

At index [1], both elements are identified, but at index [2], nothing is identified. The key difference between the two is that one has display:none, and the other has display:block. However, their involvement in determining these fields is minimal due to ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

The npm package for @azure/storage-blob doesn't seem to play nice with the Azure Blob storage modules for IoT Edge

Currently, I am developing an edge module using Node.js to interact with Azure Blob storage modules on IoT Edge platform. To achieve this, I am following the documentation available at https://www.npmjs.com/package/@azure/storage-blob. The npm package ut ...

The dimensions of the pop-up window in Chrome's JavaScript are not displaying correctly

My goal is to launch a new chat room window on our website. The dimensions of the chat room are set to 750px x 590px. Below is the link I am using to trigger the javascript popup. <a href="javascript:void(0)" onclick="window.open('http://gamersuni ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

I am unable to eliminate the parentheses from the URL

I am in need of creating a function that can extract the content inside "()"" from a URL: Despite my efforts, the function I attempted to use did not provide the desired result. Instead of removing the "()" as intended, it encoded the URL into this format ...

Unable to recreate the Jquery Mobile Autocomplete demonstration

Attempting to recreate a demo using my own remote data source: The HTML page mirrors the demo, with one change: url: "http://localhost/sample.php", Here is the dummy remote data source sample.php <?php $a = array('apple', 'mango&apo ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

Guide to setting up sub-routes in fastify

Currently, I am incorporating fastify as the web framework for my nodejs project. My aim is to organize and call all routes from a specific directory while having a base route established in the main JS file, similar to how it's done in express. Despi ...

Surprising outcome arising from simultaneous execution of numerous asynchronous operations on every individual object within an array

I'm fairly new to working with Node.js and I'm still trying to grasp the concept of callbacks and the asynchronous nature of Node.js. However, I've encountered a problem that I can't seem to solve. I've already searched extensively ...

"Upon refreshing, the background image reverts back to its original default setting

With React, I have implemented a feature where users can navigate to their 'settings' page and select an image to set as their background. I used DOM manipulation to achieve this functionality successfully! However, whenever the page is refreshed ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Invalid web address entered

While attempting to incorporate a functionality that opens a new window to a specific link when clicking an icon, I encountered an issue where the click action redirects to the wrong URL. Instead of directing to the URL specified in its href attribute, it ...