By default, HTML tables should remain hidden when the checkbox is already checked

By default, the checkbox is checked but the tables are not hidden. Initially, the first two tables will be visible. When you click a few times, you'll see hidden tables, but they should remain hidden by default. Do I need to call a function or change a parameter in the function?

function showMe(cls) {
    var chboxs = document.getElementsByName("c1");
    var vis = 0;
    for (var i = 0; i < chboxs.length; i++) {
        if (chboxs[i].checked) {
            vis = 1;
            break;
        }
    }
    var elements = document.getElementsByClassName(cls);
    for (let e of elements) {
        if (vis === 1) {
            e.style.display = 'none';
        } else {
            e.style.display = 'table';
        }

    }
}
<table class="header" width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td align="left">
            <input type="checkbox" name="c1" checked="true" onclick="showMe('box')">Show Result
        </td>
    </tr>
</table>

<table class="uniqueborder" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0">
...
// Rest of the HTML code

Answer №1

To easily display the content on page load, you can simply execute the showMe('box') function:

function showMe(cls) {
  var chboxs = document.getElementsByName("c1");
  var vis = 0;
  for (var i = 0; i < chboxs.length; i++) {
    if (chboxs[i].checked) {
      vis = 1;
      break;
    }
  }
  var elements = document.getElementsByClassName(cls);
  for (let e of elements) {
    if (vis === 1) {
      e.style.display = 'none';
    } else {
      e.style.display = 'table';
    }
  }
}

showMe('box');
<table class="header" width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td align="left">
      <input type="checkbox" name="c1" checked="true" onclick="showMe('box')">Show Result
    </td>
  </tr>
</table>

<table class="uniqueborder" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0">
  <tr>
    <td class="uniqueborder" width="90%" align="center" bgcolor="#F3F3F3"><b>Event</b></td>
    <td class="uniqueborder" width="10%" align="center" bgcolor="#F3F3F3"><b>Status</b></td>
  </tr>
  <tr>
    <td class="uniqueborder" align="left">
      <p style="margin: 0pt; ">Test </p>
    </td>
    <td class="uniqueborder" align="center" width="10%">
      <font color="gray">N/A</font>
    </td>
  </tr>
  <tr>
    <td class="uniqueborder" align="left">
      <p style="margin: 0pt; ">Test </p>
    </td>
    <td class="uniqueborder" align="center" width="10%">
      <font color="gray">N/A</font>
    </td>
  </tr>
  </tbody>
</table>
...
</table>

A more effective method is to eliminate inline onclick events and attach an unobtrusive change event listener to checkboxes. This way, you can trigger the event during page load for better performance.

It's worth noting that this alternative approach removes the need for the initial loop in your script. Here's how you can implement it:

jQuery($ => {
  $('.show').on('change', e => {
    var targetClass = $(e.target).data('targetclass');
    $('.' + targetClass).toggle();   
  }).trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="header" width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td align="left">
      <input type="checkbox" name="c1" checked="true" class="show" data-targetclass="box">Show Result
    </td>
  </tr>
...

</table>

Additionally, it's recommended to avoid inline CSS styling and attributes like width, cellpadding, etc. Instead, use external stylesheets for a cleaner structure. Also, refrain from using deprecated elements such as font.

Answer №2

The details are in the HTML file I provided, but it's not functioning properly when I try to call showMe('box') in JavaScript.

<script language="JavaScript">

function showMe(cls) {
    var chboxs = document.getElementsByName("c1");
    var vis = 0;
    for (var i = 0; i < chboxs.length; i++) {
        if (chboxs[i].checked) {
            vis = 1;
            break;
        }
    }
    var elements = document.getElementsByClassName(cls);
    for (let e of elements) {
        if (vis === 1) {
            e.style.display = 'none';
        } else {
            e.style.display = 'table';
        }

    }
}
show('box');
</script>

</head>


                <br>
                <table class="header" width="100%" border="0" cellpadding="0" cellspacing="0">
                <tr>
                <td align="left">
                <input type="checkbox" name="c1" checked="true" onclick="showMe('box')">Show Result
                </td>
                </tr>
                </table>
                
                <table class="uniqueborder" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0">
                <tr>
                <td class="uniqueborder" width="90%" align="center" bgcolor="#F3F3F3"><b>Event</b></td>
                <td class="uniqueborder" width="10%" align="center" bgcolor="#F3F3F3"><b>Status</b></td>
                </tr>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; ">Test </p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; ">Test </p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                </tbody></table>
                <table class="box" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0"><tbody>
                    <tr>
                        <td style="border-right:1px solid #CBCBCB; padding-left:2px; padding-right:2px"align="left"><p style="margin: 0pt; ">Test </p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>

                </tbody></table>
                <table class="box" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0"><tbody>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Test input:</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Expected</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                                    </tbody></table>
                <table class="uniqueborder" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0"><tbody>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Test input:</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Expected</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                                    </tbody></table>
                <table class="box" width="100%" bordercolor="#CBCBCB" cellpadding="0" cellspacing="0"><tbody>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Test input:</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                    <tr>
                        <td class="uniqueborder" align="left"><p style="margin: 0pt; "><span class="bluebold">1. Expected</span></p></td>
                          <td class="uniqueborder" align="center" width="10%"><font color="gray">N/A</font></td>
                    </tr>
                    
                </tbody></table></table>

</html>

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

Switching the audio file upon button click

I've been attempting to switch the audio file when a button is clicked but I keep encountering this error Uncaught TypeError: audio.load is not a function Below is my code, where the goal is to change the audio file upon pressing the button. If ...

How to create a border using a repeated image with spacing between each repetition

Is there a way to create a dashed horizontal line from an image and adjust the spacing between each dash using HTML and CSS? I feel like using javascript for this would be excessive. https://i.sstatic.net/YiD9q.png I'm encountering this issue with t ...

Encountering issues with Vue routing while utilizing webpack. The main page is functional, however, subpaths are resulting in

Before implementing webpack, my vue routing was functioning properly. However, I encountered several loader issues and decided to use webpack. After setting up webpack, the main page loads correctly, but all of my routes now result in a 404 error. I have ...

The heap limit has been reached in Github Actions, causing an allocation failure

Encountering a heap out of memory error in Github Action during the last "run: npm run build". FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory Error: Process completed with exit code 1. Showcasing the workflow file: name: ...

How can you access the input value from load dash's debounce function in a Vue.js application?

Is there a way to capture the input entered during the @typing event of the b-autocomplete component in Buefy? During the @typing event, the debounce method is called with specific parameters as shown below- <b-field label="Location"> ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...

The HTML content I created is too large for the screen and is extending beyond its borders

The navigation bar and footer on my HTML page adjust themselves according to the screen width, but the main content is not adjusting properly. I tried using a media query for mobile resolution (517px), but when I tested it on a PC with a smaller screen wi ...

JavaScript: The most efficient method for locating a Regular Expression within an Object's properties

Suppose I have a scenario where I need to validate if the words in an array exist in a dictionary and take certain actions accordingly. Here's a snippet of the code that achieves this: let dictionary = { aaa : 'value1', bbb : 'val ...

Is there a way to maintain consistent height among vertical divs?

Is it possible to create a ranking system that adjusts based on the user's points while maintaining consistent height with an image? How can I eliminate the br tags in this scenario? <!DOCTYPE html> <html lang="en>" <head> <m ...

What could be causing AJAX to consistently return identical data to the callback function when distinct objects are supplied as arguments?

I am attempting to make two separate calls to an MVC controller. The first call returns a series of data, while the second call returns a partial view. When I check in Firebug, both calls show "success" status. I am trying to utilize a callback function t ...

Flexible layout design for mobile devices

Check out how my desktop page looks: Desktop version If you want to see how it should appear on mobile, click here: Mobile Version This is the HTML/CSS code for the desktop version, and everything seems to be working fine. .skills { width: 80%; ba ...

When a button is clicked in (Angular), it will trigger the highlighting of another button as a result of a value being modified in an array. Want to know the

Currently in the process of developing a website with Angular, I've encountered an unusual bug. The issue arises when using an *ngFor div to generate twelve buttons. <div *ngFor = "let color of colors; let i = index" style = "display ...

Screen rendering can be a challenging task

As I dive into learning how to use THREE.js for creating browser games, I've encountered a roadblock. Every time I attempt to import a model using the code, the screen just renders black. Surprisingly, I've been smoothly coding and running it in ...

When a PHP-generated child element is clicked, jQuery fails to detect it

I'm currently developing a website where I need to dynamically display buttons based on database content. These buttons, when clicked, should send a request to the database and update the page content accordingly. My approach involves using Ajax and ...

React does not support having two :focus selectors on a single JSX element

I'm working with a React script that includes a specific element. I want to apply more than one :focus-within selector in CSS, but for some reason only the dropdown selector is being expressed when I focus on the element. Here's the code: React J ...

Sending data from Ajax to PHP on the same page

<!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8"> <title>AJAX Testing</title> <!-- jQuery Library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> ...

Generate an array of objects based on the attributes of img elements, extract their values, and display them using jQuery

I currently have a fullscreen plug-in that works with static URLs, but I want to switch to using dynamic image data generated by a CMS on the page. Here is a snippet of the HTML output from the CMS: <ul class="large-gallery"> <li> <a href ...

Is there a way to see the default reactions in a browser when keyboard events such as 'tab' keydown occur?

Whenever I press the 'tab' key, the browser switches focus to a different element. I would like to be able to customize the order of focused elements or skip over certain elements when tabbing through a page. While I am aware that I can use preve ...

Refreshing only a part of the page without the need to refresh the entire page

One issue I'm facing is that I have a partial that renders correctly, but I would like to update it without affecting the rest of the page. Below is my current code snippet: rolls_controller: def check_server Roll.find(params[:id]).update(:statu ...

Execute the function if the element has a specific class; otherwise, execute a different function

Currently, I am working on a page where I need to make an element draggable. Upon clicking on the element, I add the 'active' class which expands the div along with the image inside it. Initially, the div is structured as... <div class="wor ...