3

I'm having trouble getting the accordion aspect of my HTML page to work.

Problems:

  1. Clicking the 'Expand All' (which turns into 'Collapse All') is not working.
  2. When I click the '+' (next to the heading) it expands the heading, but clicking the + on another heading (while one is already expanded), causes the previous one (or all) to close, and only open the one just selected. I need the tabs to stay open, or close only when the user clicks on the '-' or clicks the 'Expand all/Collapse All' button.

Note: I have included the full JS, including other functions as I thought the conflict may be there?

Here is the JSFiddle

Please help, thank you!

JS

var testing = {
  
    BContactUs: function() {
      var businessForm = document.getElementById('businesscontactus_form');
      const companyName = document.getElementById('companyName');
      const bRName = document.getElementById('bRName');
      const cPosition = document.getElementById('cPosition');
      const bEmail = document.getElementById('bEmail');
      const bMessage = document.getElementById('bMessage');
  
      businessForm.addEventListener('submit', e => {
        e.preventDefault();
  
        checkInputs();
      });
  
      function checkInputs() {
        // trim to remove the whitespaces
        const companyNameValue = companyName.value.trim();
        const bRNameValue = bRName.value.trim();
        const cPositionValue = cPosition.value.trim();
        const bEmailValue = bEmail.value.trim();
        const bMessageValue = bMessage.value.trim();
  
        if (companyNameValue === '') {
          setErrorFor(companyName, 'Company Name must be entered');
        } else {
          setSuccessFor(companyName);
        };
  
        if (bRNameValue === '') {
          setErrorFor(bRName, 'Name cannot be blank');
        } else {
          setSuccessFor(bRName);
        };
  
        if (bEmailValue === '') {
          setErrorFor(bEmail, 'Email cannot be blank');
        } else if (!isEmail(bEmailValue)) {
          setErrorFor(bEmail, 'Not a valid email');
        } else {
          setSuccessFor(bEmail);
        };
  
        if (cPositionValue === '') {
          setErrorFor(cPosition, 'C position cannot be blank');
        } else {
          setSuccessFor(cPosition);
        };
  
        if (bMessageValue === '') {
          setErrorFor(bMessage, 'Message cannot be blank');
        } else {
          setSuccessFor(bMessage);
        };
      };
  
      function setErrorFor(input, message) {
        const formControl = input.parentElement;
        const small = formControl.querySelector('small');
        formControl.className = 'bus-form-control error';
        small.innerText = message;
      };
  
      function setSuccessFor(input) {
        const formControl = input.parentElement;
        formControl.className = 'bus-form-control success';
      };
  
      function isEmail(bEmail) {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(bEmail);
      };
    },
    CustomerContactUs: function() { 
      const customer_contactus_form = document.getElementById('customercontactus_form');
      const cCUName = document.getElementById('cCUName');
      const cCUSubject = document.getElementById('cCUSubject');
      const cCUEmail = document.getElementById('cCUEmail');
      const cCUMessage = document.getElementById("cCUMessage");
      const cCUDisclaimerBox = document.getElementById('cCUDisclaimerBox');
  
      customer_contactus_form.addEventListener('submit', e => {
        e.preventDefault();
  
        checkcustomerCU_Inputs();
      });
  
      function checkcustomerCU_Inputs() {
        //trim to remove the whitespaces
        const cCUNameValue = cCUName.value.trim();
        const cCUSubjectValue = cCUSubject.value.trim();
        const cCUEmailValue = cCUEmail.value.trim();
        const cCUMessageValue = cCUMessage.value.trim();
  
        if (cCUNameValue === '') {
          setErrorForCU(cCUName, 'Please enter your name');
        } else {
          setSuccessForCU(cCUName);
        };
  
        if (cCUSubjectValue === '') {
          setErrorForCU(cCUSubject, 'Please enter a subject in order for us to help you better.');
        } else {
          setSuccessForCU(cCUSubject);
        };
  
        if (cCUEmailValue === '') {
          setErrorForCU(cCUEmail, 'Email cannot be blank');
        } else if (!isEmail(cCUEmailValue)) {
          setErrorForCU(cCUEmail, 'Not a valid email');
        } else {
          setSuccessForCU(cCUEmail);
        };
  
        if (cCUMessageValue === '') {
          setErrorForCU(cCUMessage, 'Please enter a message.');
        } else {
          setSuccessForCU(cCUMessage);
        };
  
        if (!cCUDisclaimerBox.checked) {
          setErrorForCU(cCUDisclaimerBox, 'Please check box and accept terms and conditions.');
        } else {
          setSuccessForCU(cCUDisclaimerBox);
        };
      };
  
      function setErrorForCU(input, message) {
        const formControlCU = input.parentElement;
        const small = formControlCU.querySelector('small');
        formControlCU.className = 'cus-form-control error';
        small.innerText = message;
      };
  
      function setSuccessForCU(input) {
        const formControl = input.parentElement;
        formControl.className = 'cus-form-control success';
      };
  
      function isEmailCU(cCUEmail) {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(cCUEmail);
      };
    }
  };
  
  
  $(document).ready(function() {
  
    $(".cp_exin_expandAll").on("click", function() {
      var accordionId = $(this).attr("accordion-id"),
        numPanelOpen = $(accordionId + ' .collapse.in').length;
  
      $(this).toggleClass("active");
  
      if (numPanelOpen == 0) {
        openAllPanels(accordionId);
      } else {
        closeAllPanels(accordionId);
      }
    })
  
    openAllPanels = function(aId) {
      console.log("setAllPanelOpen");
      $(aId + ' .panel-collapse:not(".in")').collapse('show');
    }
    closeAllPanels = function(aId) {
      console.log("setAllPanelclose");
      $(aId + ' .panel-collapse.in').collapse('hide');
    }
  
  });

HTML

<!doctype html>
<html lang="en">

  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <!-- Latest compiled and minified CSS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js " integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW " crossorigin="anonymous "></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <title>Extra Info</title>
  </head>

  <body>
    <header></header>

    <div class="extrainfo_outerbackground">
      <div class="extrainfo_banner">
        <h3 class="form-heading">Lorem Ipsum</h3>
        <a href="javascript:void(0)" class="cp_exin_expandAll active" accordion-id="#accordion"></a>
      </div>
      <div class="clearfix"></div>
      <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingOne">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                Collapsible Group Item #1
              </a>
            </h4>
          </div>
          <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
            <div class="panel-body">
              <br>
              <p>
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
                on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
              </p>
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingTwo">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
                Collapsible Group Item #2
              </a>
            </h4>
          </div>
          <div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingThree">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
                Collapsible Group Item #3
              </a>
            </h4>
          </div>
          <div id="collapseThree" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingThree">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingFour">
            <h4 class="panel-title">
              <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="true" aria-controls="collapseFour">
                Collapsible Group Item #4
              </a>
            </h4>
          </div>
          <div id="collapseFour" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFour">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingFive">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseFive" aria-expanded="true" aria-controls="collapseFive">
                Collapsible Group Item #5
              </a>
            </h4>
          </div>
          <div id="collapseFive" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFive">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingSix">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseSix" aria-expanded="true" aria-controls="collapseSix">
                Collapsible Group Item #6
              </a>
            </h4>
          </div>
          <div id="collapseSix" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSix">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingSeven">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseSeven" aria-expanded="true" aria-controls="collapseSeven">
                Collapsible Group Item #7
              </a>
            </h4>
          </div>
          <div id="collapseSeven" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSeven">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>

  <footer></footer>

  <script src="js/script.js"></script>
</html>
Ricardo
  • 3,696
  • 5
  • 36
  • 50
Adam Lansome
  • 105
  • 9
  • It seems like the code for `BContactUs` and `CustomerContactUs` add extra complexity that are not necessary to help finding the answer. The bug should be in the logic on the `$(document).ready` callback or on API usage – Ricardo Mar 22 '21 at 18:26
  • Please double check the logic in `$(aId + ' .panel-collapse:not(".in")').collapse('show');` you may have negated more things you wanted! – Ricardo Mar 22 '21 at 18:26
  • @Ricardo - I've checked it. This isn't the problem -it all works fine if I separate the JS ($(document).ready -which is for the Collapse/Expand) and put in a different file, but that defeats the purpose. How do I add it as a function to the namespace which has the 'BContactUs' and 'CustomerContactUs', do you think that might be the solution? – Adam Lansome Mar 22 '21 at 18:55
  • Oh, so this sounds like a [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) loading issue. Can you try [putting jQuery](https://stackoverflow.com/questions/2105327/should-jquery-code-go-in-header-or-footer#:~:text=All%20scripts%20should%20be%20loaded,just%20before%20.) just before `

    `?

    – Ricardo Mar 23 '21 at 18:14

2 Answers2

0

This sounds like a script loading issue. Can you try moving jQuery after the HTML content, just before </body>?

Something like this may fix it:

HTML

<!doctype html>
<html lang="en">

  <head>
    <!--  Metadata, Stylesheets, Favicons, etc... -->
    <!-- ... -->    
  </head>

  <body>
    <!-- Content to create the initial DOM Tree-->
    <div class="extrainfo_outerbackground">
       <!-- ... -->
    </div>

    <!-- Scripts that manipulate the previously created DOM elements -->
    <!-- Double check order -->
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <!-- ... -->
    <script src="js/script.js"></script>
  </body>

</html>
Ricardo
  • 3,696
  • 5
  • 36
  • 50
  • Gave it a shot, but made no difference. The same problems persist. Any other ideas? – Adam Lansome Mar 24 '21 at 11:59
  • I said that because you mentioned about it working when moving things out of the HTML. I'm sorry it didn't help, but it may be a variation of that. Could you post your code in an online tool like [codepen.io](https://codepen.io/) this may help get more people looking into it and trying to troubleshoot it? – Ricardo Mar 24 '21 at 23:10
  • Thanks. I've thrown up the link to JS Fiddle, if anyone can help, much appreciated! – Adam Lansome Mar 25 '21 at 13:26
  • The [API DOCS](https://getbootstrap.com/docs/4.3/components/collapse/) don't mention about usin the `.in` class. Can you remove it from the HTML and from the JS code?? – Ricardo Mar 26 '21 at 21:37
0

The API DOCS don't mention about using the .in class. So I believe it's not part of the API (internal use only?)

Instead of

 <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">          

Try not adding the in class for all the DIV.panel-collapse:

 <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">

Then, any the following programatic calls work as expected:

$(aId + ' .panel-collapse').collapse('show');
$(aId + ' .panel-collapse').collapse('hide');
$(aId + ' .panel-collapse').collapse('toggle');

You also need to review other parts of your code, but this gives you an idea.

E.g. use the show class instead of in for reading state:

numPanelOpen = $(accordionId + ' .collapse.show').length;

Here a working version (you need to tweak if to fulfill all of your requirements) https://jsfiddle.net/0syhjnpk/

Ricardo
  • 3,696
  • 5
  • 36
  • 50
  • Thanks, but this made no difference. As mentioned independently it works fine. – Adam Lansome Mar 29 '21 at 10:32
  • It worked for me after editing on your JSFiddle – Ricardo Mar 29 '21 at 18:27
  • the problem with your solution is when you try to open the headings individually, only one will open at a time for example if I want to read #1 and then #3 only the latter will expand, but #1 will collapse automatically as I open it. – Adam Lansome Mar 30 '21 at 16:01
  • I believe that is the expected behavior when you use `data-parent="#accordion"` to each item. Double check [this section](https://getbootstrap.com/docs/4.3/components/collapse/#via-data-attributes) on the API. If you don't want the accordion-like behavior, just remove this attribute from all. – Ricardo Mar 31 '21 at 21:16
  • What doesn't make sense is if I have this seperated from the main project then it works completely. So it should work as is – Adam Lansome Apr 01 '21 at 13:47
  • If the `.in` class is not part of the API, using it and/or understanding odd behaviors when using it may require looking into their internal code. Be prepared to maintain it in case you upgrade the library later, as there is no "contract" that internal structures won't change. – Ricardo Apr 06 '21 at 19:52
  • 1
    Regarding the different behaviors in load, maybe you can create a separate question showing both the working and non-woking code in JSFiddles for comparison. You could simplify even more the examples by removing all the unessential details (e.g. having only 3 items vs. the original 7). Once you're working on removing code that is not relevant to your specific question, you may accidentally find the answer – _Aha, this is the code that caused the issue!_ – Ricardo Apr 06 '21 at 20:03
  • 1
    This was really helpful, appreciate the time you put into this. – Adam Lansome Apr 12 '21 at 19:50