Prevent collapsing when clicking twice

This section is designed to collapse and expand in its default mode. It will close when the user selects "No" and open/close when the user selects "Yes".

I am looking to modify it so that it only closes when the user picks "No" and reopens only when the user chooses "Yes". If the user selects "Yes" again, it should remain in the open state.

Check out the JSFiddle DEMO

jQuery('.btn-active').click(function(e) {
          jQuery('.collapse').collapse('hide');
        });
      
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="btn-group btn-group-toggle d-flex btn-active " data-toggle="buttons">
        <label class="btn btn-primary w-100 active" data-toggle="collapse" data-target="#expolicy">
          <input type="radio" name="options" id="option1" autocomplete="off"> Yes
        </label>
        <label class="btn btn-primary w-100">
          <input type="radio" name="options" id="option2" autocomplete="off"> No
        </label>
      </div>
    </div>
    <div class="col-12">
      <div class="collapse show" id="expolicy">
        This is the collapsible content. It will only close when "No" is selected and reopen when "Yes" is chosen. It remains open by default.
      </div>
    </div>
  </div>
</div>

Answer №1

Upon clicking the label, the click event is triggered, hence I have assigned a distinct id to each label for clarity.

Furthermore, I have eliminated the unnecessary data-toggle attribute from the Yes button. This ensures that only the function controls the collapsing functionality.

Within the function, it determines which button (yes or no) was clicked and executes the appropriate actions accordingly.

jQuery('.btn-active').click(function(e) {  
  if (e.target.id == "showCollapse"){ 
    jQuery('.collapse').collapse('show');
  } else if (e.target.id == "hideCollapse"){
    jQuery('.collapse').collapse('hide');
  }
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="btn-group btn-group-toggle d-flex btn-active " data-toggle="buttons">
        <label class="btn btn-primary w-100 active" data-target="#expolicy" id="showCollapse">
          <input type="radio" name="options" id="option1" autocomplete="off"> Yes
        </label>
        <label class="btn btn-primary w-100" id="hideCollapse">
          <input type="radio" name="options" id="option2" autocomplete="off"> No
        </label>
      </div>
    </div>
    <div class="col-12">
      <div class="collapse show" id="expolicy">
        This is the collapse. It opens/closes when the user clicks "Yes". It should close only when the user clicks "No" and open only when the User clicks "Yes". It is open by default.
      </div>
    </div>
  </div>
</div>

Answer №2

You may also want to consider using two distinct classes like .btn-active1 and .btn-active2

Additionally, make sure to eliminate the data-target="toggle"

jQuery('.btn-active1').click(function(e) {
  jQuery('.collapse').collapse('show');
});
jQuery('.btn-active2').click(function(e) {
  jQuery('.collapse').collapse('hide');
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>

<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="btn-group btn-group-toggle d-flex" data-toggle="buttons">
        <label class="btn btn-primary w-100 active  btn-active1" data-toggle="" data-target="#expolicy">
          <input type="radio" name="options" id="option1" autocomplete="off"> Yes
        </label>
        <label class="btn btn-primary w-100  btn-active2">
          <input type="radio" name="options" id="option2" autocomplete="off"> No
        </label>
      </div>
    </div>
    <div class="col-12">
      <div class="collapse show" id="expolicy">
        This is the collapse. It opens/closes when the user clicks "Yes". It should close only when the user clicks "No" and open only when the User clicks "Yes". It is open by default.
      </div>
    </div>
  </div>
</div>

Answer №3

To ensure proper functionality without interfering with Bootstrap controls, it is necessary to remove the attributes data-toggle and data-target from the "Yes" label. Instead, assign the values "Yes" and "No" to their respective radio buttons and attach a click event handler to the labels. Based on the selected radio button value, you can show or hide the collapsible div.

jQuery(document).ready(function(){
 jQuery('label.w-100').click(function(e) {
   var value = $(this).find('input[type=radio][name=options]').val();
   if(value=='Yes') {
     jQuery('#expolicy').collapse('show');
   } else {
     jQuery('#expolicy').collapse('hide');
   }
  });
});

View JSFiddle Demo

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

Utilize Css3 MediaQueries to nudge @Media switch for hyperlinks

My website currently utilizes css3-mediaqueries.js for a mobile-friendly design, which is working well. However, some users are still requesting to view the "web-version" instead. Is there a way to override the current CSS on the homepage, specifically the ...

Trouble with z-index property within the confines of the <ion-segment-button></ion-segment-button> tag

The z-index property seems to be having no effect on the elements within the ion-segment-button. I attempted to adjust the positions of the elements and set the z-index to 999999 with the button z-index set to -1. However, this solution did not work as ex ...

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

"Sticky Top Button That Stays in Place When Scrolling | Innovative CSS & jQuery

I've been inspired by the "Proceed to checkout" button on amazon.com and I want to recreate it. However, I'm facing a challenge as their website is not responsive and I can't find a way to view a device user agent in Chrome. To see what I&ap ...

The functionality of Angular services is not available for use in Jasmine tests

As someone who is relatively new to Jasmine Testing and the Angular framework, I find myself in a unique situation. I am currently struggling with referencing my service functions in my Jasmine tests. Here is a snippet of my Angular Service Initialization ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

Retrieving data from an Ajax request

I am struggling with extracting the HP and PCP Payment fields from the JSON string obtained through a Jquery Ajax request: function DoPaymentSearch() { var start,end; start=Date.now(); var getQuotesSuccess = function(results){ end=Date.now(); alert(JSON.s ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

"Learn how to automatically limit date selection to a maximum of 3 days after choosing a date with the nb-rangepicker rangep

I have successfully implemented the nebular date range picker to filter data. However, I am facing an issue with setting the default maxDate 3 days after selecting the input. I have tried multiple methods but none have worked for me. Below is my TypeScript ...

Automatically populate textboxes with database information based on selected combobox item without the need to refresh the page

I would like to implement a feature where textboxes are automatically filled from a database when a user selects an option from a combo box. This can be achieved using jQuery or JavaScript in PHP. Once a user selects an element, the corresponding text sh ...

Issue with RN-fetch-blob regarding base64 encoding specifically on Android devices

I've encountered an issue in React Native where I'm trying to download a base 64 string from an API and display it as a PDF on mobile devices. The problem arises when using the code on Android, as it returns a 'bad base 64' / invalid P ...

New jQuery div elements do not have animations when using $(document).on

After creating an animation function that worked well with hovering over squares and leaving a trail, I later needed to add or remove squares based on the page size. Seeking help from here, I discovered my bind animation function wouldn't work on new ...

Modifying the color of a placeholder in an HTML input using CSS

Version 4 of Chrome now supports the placeholder attribute on input[type=text] elements (and likely other browsers do too). Despite this, the following CSS code does not affect the color of the placeholder text: input[placeholder], [placeholder], *[pla ...

Filling an HTML modal with either keys or values from a JSON array

I'm facing a simple issue that I can't seem to solve. What am I missing here? I receive a PHP array through JSON encoding: var curr_op = <?php echo json_encode($options) ?>; When I console.log(curr_op), it shows: [14:35:00.889] ({' ...

When I submit the form, my goal is to automatically focus on the next text input field

When rendering text inputs for player names by mapping the components and passing down the player number, I aim for a functionality where the user can simply hit enter and have the screen focus on the next input. One attempt that I made is as follows: & ...

Expanding an item to fill the entire width within a Bootstrap navigation bar

Here is the layout of the navigation bar in my current web application project: [ Brand [button] [button] [----- input field -----] ----- empty space ----- [button] ] This is a simplified version of the code I am working with: <div class="container-f ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

The Angular function fails to execute when clicked

I am trying to trigger a new page launch when a cube is clicked using Angular. Unfortunately, my current code doesn't seem to be working as expected and nothing happens when I click the cubes. This makes me wonder if there is something wrong with my i ...

Issue with AJAX and Jquery auto form update functionality malfunctioning

On my form page, here is the code snippet: <form action="/register-process" method="post" id="form1"> <script type="text/javascript"> jQuery(document).ready(function($) { $(document).on('focusout', '#dateenglish', function ...