Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by...

function getItem(id) {
    var itm = false;
    if(document.getElementById)
        itm = document.getElementById(id);
    else if(document.all)
        itm = document.all[id];
    else if(document.layers)
        itm = document.layers[id];
    return itm;
}
function showHideItem(id) {
    itm = getItem(id);
    if(!itm)
        return false;
    if(itm.style.display == 'none')
        itm.style.display = '';
    else
        itm.style.display = 'none';
    return false;
}

It functions correctly when loading a new address form, but I encounter an issue if the form is submitted with the checkbox checked and validation fails. When the form reloads with the checkbox still checked, unfortunately, the fields remain visible, so unchecking the checkbox hides the fields!

<tr><td class="white"><strong>Delivery Address</strong></td>
    <td>Tick <input Type="checkbox" id="deliver_same" value="yes" onClick="showHideItem('delAddress')" />
  If delivery address is billing address</td></tr>
    <tbody id="delAddress">
    <tr><td>Address line 1</td><td><input class="text" name="saddr1" value="" /></td></tr>
    ...
    <tr><td>Post /Zip Code</td><td><input class="text" name="spostalcode" value="" /></td></tr>
</tbody>

I believe what I require is an onload event that hides the fields if the checkbox is checked when the form loads. After writing that, I might attempt it myself but am not entirely confident. Please refrain from mentioning jQuery as it is not an option at this stage of the project.

Answer №1

function toggleDeliveryAddress() {
    var deliverSame = getItem('deliver_same');
    var deliveryAddress = getItem('delAddress');
    if (deliverSame.checked) {
        deliveryAddress.style.display = 'none';
    } else {
        deliveryAddress.style.display = 'block';
    }
}
toggleDeliveryAddress();  /* This function is executed when the page loads */

Include the above function, as well as your getItem function, just before the closing </body> tag. Then, call it within the checkbox input onclick event. Ensure to update the element with ID delAddress from a tbody to a div so that the getItem function can target it accurately.

For reference, visit this interactive demo: http://jsfiddle.net/JuNhN/1/

Answer №2

I have enhanced Josh's function by making it more adaptable and have opted for using document.getElementById() as it seamlessly integrates with itm.style.display. I have reservations about checkDeliverSame(); therefore, I am leaning towards directly calling it in the HTML code right after the closing tag.

function verifyHiddenRows(id) {
    deliverSame = getItem('deliver_same');
    itm = document.getElementById(id);
    if (deliverSame.checked == true) {
        itm.style.display = 'none';
    } 
}

<script>verifyHiddenRows('deliveryAddress');</script>

The form is now functioning precisely as intended.

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

Is `html.fa-events-icons-ready` causing clutter and disrupting the layout of the body?

I am seeking some clarification on my code and the resulting issues it is causing. Check out this image for reference: https://i.stack.imgur.com/jBQYd.png Why is the body height not taking up 100% of the space? The background image appears to be affect ...

ng-animate causing an impact on the input element, even though it is not supposed to

As a newcomer to angularjs, I'm facing a challenge in animating only specific elements within my app. To achieve this, I have included the ngAnimate module in my app setup: var mrApp = angular.module("mrApp", ["ngRoute", "ngAnimate", "templates"]); ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Content editable div causing overflow issues in Internet Explorer

I am having trouble with a content editable div where the text is not wrapping properly. I attempted to use "overflow:scroll" but it only ends up cutting off the text horizontally. https://i.stack.imgur.com/WlMdY.jpg ...

The pointer-events attribute seems to be inactive and not functioning as expected

I recently implemented a design feature on my website where I created a transparent div at the bottom of the page to overlay a fixed div. The idea was for the fixed div to be revealed as the user scrolled down, but unfortunately, it seems that the click ev ...

Issues with iFrame Alignment

I recently created a digital catalog using FlipHTML5 and realized it needed to be more mobile-friendly. To address this issue, I included the following CSS: .size { width: 85vw; height: 75vh; Although this adjustment made the catalog display correctly on ...

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...

Encountering an issue: Module not found - 'cryptile' during express js installation

Just dipping my toes into the world of Node.js and I'm encountering some obstacles when trying to install Express.js. Seeking assistance in resolving this issue and successfully setting up Express.js. https://i.stack.imgur.com/PlHiB.png Interestingl ...

Removing a record from a database using ASP.NET MVC 5

Looking for some insight on the behavior of my JavaScript and Action in the Controller. Below are the current code snippets: Index.chtml @model IEnumerable<WebSensoryMvc.Models.SessionData> @{ ViewBag.Title = "Index"; Layou ...

Does a React functional component continuously re-render if it contains a child component?

For the past few days, I've been facing a performance issue in a React app (specifically React Native). The core of the problem is this: Whenever a function component Parent has another function component as its Child, the Parent will consistently re ...

Two miniature tables placed next to each other within a single cell, both sharing equal height

Is there a way to make two tables within a parent table cell have the same height using HTML and CSS? If one cell has more content than the other, is it possible to adjust the height of both tables accordingly? <table cellpadding="0" border="1" cell ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

Styling Scrollbars in Datatables

I need assistance on styling a specific datatable scrollbar using Webkit. Below is the code snippet: id ::-webkit-scrollbar-track { background-color: transparent; border-radius: 5px; } id::-webkit-scrollbar { width: 13px; } ...

Using HTML5 to Define the Size of a File Upload Button

The validation error from W3C states: "Attribute size is not permitted for the input element at this location." <input type="file" name="foo" size="40" /> How should the width of a file input be specified in HTML5? ...

Tips for organizing and concealing images within a Div for seamless transitions (no need for floats)

Currently, I am working on a grid layout for my website. My goal is to have 9 images load quickly, and then once the page has loaded, I want to fetch additional images, insert them into the image containers, and animate between them. While I understand how ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

Is there a method to preserve the pressed/focused state when moving from one input box to the next?

While creating a form for a client, I encountered a requirement where the input box should change once clicked and retain that change even after it has been filled and the user moves to the next input box. Is there a way to achieve this using only HTML & C ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

Is it possible to load HTML content within a Sweet Alert pop-up

Below is the code I am using to call Swal: window.swal({ title: "Checking...", text: "Please wait", imageUrl: "{{ asset('media/photos/loaderspin.gif') }}", showConfirmButton: false, allowOutsideClick: false }); $.ajax({ t ...