skip to Main Content

I’m a little stumped here. I’m using pure JavaScript, no jQuery.

I want to change the innerHTML of a heading between two values when a checkbox is selected. I have it working when the checkbox is selected, but unchecking the checkbox does not switch it back.

JSFiddle!

HTML

<h2 id="billing-information-header"></h2>

<p id="before-billing">Please enter your billing information below. Shipping to a different address? Check the box below the billing fields.</p>

<h2>SHIPPING INFORMATION:</h2>

<input id="ship-to-different-address-checkbox" type="checkbox" name="ship_to_different_address"><span>Ship to a Different Address?</span>

JS:

window.addEventListener('load', function() {
        const checkBox = document.querySelector('#ship-to-different-address-checkbox');
        const heading = document.querySelector('#billing-information-header');
        const message = document.querySelector('#before-billing');

        heading.innerHTML = 'BILLING & SHIPPING INFORMATION:';

        checkBox.addEventListener('click', function() {
            heading.innerHTML = 'BILLING INFORMATION:';
        });

});

I’m planning on switching the heading back to ‘BILLING & SHIPPING INFORMATION” upon unchecking the box. I’m also planning on dynamically changing the message inner HTML as well.

2

Answers


  1. Use the checked property of the checkbox to determine if it’s checked

    here is the updated fiddle: https://jsfiddle.net/978ucdgt/

    window.addEventListener('load', function() {
      const checkBox = document.querySelector('#ship-to-different-address-checkbox');
      const heading = document.querySelector('#billing-information-header');
      const message = document.querySelector('#before-billing');
    
      heading.innerHTML = 'BILLING & SHIPPING INFORMATION:';
    
      checkBox.addEventListener('click', (e) => {
        heading.innerHTML = e.target.checked ? 'BILLING INFORMATION:' : 'BILLING & SHIPPING INFORMATION:'
    
      });
    
    });
    <h2 id="billing-information-header"></h2>
    
    <p id="before-billing">Please enter your billing information below. Shipping to a different address? Check the box below the billing fields.</p>
    
    <h2>SHIPPING INFORMATION:</h2>
    
    <input id="ship-to-different-address-checkbox" type="checkbox" name="ship_to_different_address"><span>Ship to a Different Address?</span>
    Login or Signup to reply.
  2. Please try the following.

    checkBox.addEventListener('click', function() {
                if(!checkBox.checked) {
                heading.innerHTML = 'BILLING INFORMATION:';
              }
              else {
                heading.innerHTML = 'BILLING & SHIPPING INFORMATION:';
              }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search