Having trouble getting the jQuery toggle function to work properly with div elements

I'm struggling with some divs that are not behaving as expected. When I click the button, it opens and changes the text to "Collapse", but when I click it again, it doesn't change the text back to "Find Support". Additionally, if I click on a different div, it will close the open one first before opening the new one. I need all divs to close when one is clicked, and for the text to change from "Collapse" to "Find Support". Can anyone offer some guidance?

$(document).ready(function () {
        $(".findButton").click(function () {         

            $(".findButton").val('Find Support');            
            $(this).val('Collapse');
            $("id^=ilsList").remove();
            $(this).closest($("#ilsList").appendTo($(this).parent()).slideToggle());          
       });        
    });

Check out the demo here.

Answer №1

Is this what you were looking for? http://jsfiddle.net/sw0zn36e/7/

<div class="DivGroup">
    <label>Bay Village Branch - <b>Cuyahoga County Public Library</b></label>
    <input type="button" onclick="LoadBranches('CuyahogaCounty')" value="Find Support" class="findButton"/>
    <div class="IlsTable" style="display:none;">
        <img src="../../Content/Images/ajax-loader.gif" style="display: none;" id="ajaxLoader"/>
        TEXT            TEXT    TEXT    
    </div>
</div>

$(document).ready(function () {
    $(".findButton").on('click', function () {
        if($(this).val() == 'Find Support') {
            $(".findButton").val('Find Support');            
            $(this).val('Collapse');
            $('.DivGroup').find('.IlsTable').slideUp();
            $(this).closest('.DivGroup').find('.IlsTable').slideDown();                        
        }
        else {
            $(".findButton").val('Find Support');
            $('.DivGroup').find('.IlsTable').slideUp();
        }                    
    });    
});

UPDATED to tackle the challenge of toggling divs. I made some modifications to the HTML structure to enhance the usability of classes. Hopefully, this solution resolves your issue!

Answer №2

~~~~~~~~~~~~~~~~~~~2nd REVIEW ~~~~~~~~~~~~~~~~~~~~~~

Alright, take a look at the revised response below:

~~~~~~~~~~~~~~~~~~~2nd REVIEW ~~~~~~~~~~~~~~~~~~~~~~

Sure, give this modification a try:

$(document).ready(function () {
$(".findButton").click(function () {      
    if ($(this).val() == 'Find Support') {   
        $('.findButton').each(function(){
            $(this).val('Find Support');
        });
        $(this).val('Collapse');            
        $(this).closest($("#ilsList").appendTo($(this).parent()).slideDown());            
    } else {       
        $(this).val('Find Support');
        $('.IlsTable').not(this).each(function(){
             $(this).slideUp();
        });
    }                
});  
});

http://jsfiddle.net/sw0zn36e/4

Answer №3

To determine if a button's previous value is different from its current one, you can use the following code snippet:

$(".findButton").click(function() {

  $(this).val(function() {
    return $(this).val() === 'Collapse' ? 'Find support' : 'Collapse';
  });
  $("id^=ilsList").remove();
  $(this).closest($("#ilsList").appendTo($(this).parent()).slideToggle());
});
#ilsList {
  display: none;
}
.IlsTable {
  background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
  clear: both;
  margin-left: 100px;
  margin-right: 100px;
  padding: 20px 60px 20px 20px;
  position: relative;
}
.trResult,
.DivGroup {
  border-top: 1px solid #ccc !important;
  float: left;
  padding: 3px 0 10px !important;
  width: 100%;
}
.DivGroup {
  padding-bottom: 3px;
}
.DivGroup label {
  font-size: 17px;
}
button:hover,
.findButton {
  border: 1px solid #333;
  color: #333;
}
button,
.findButton {
  background: none repeat scroll 0 0 rgba(0, 0, 0, 0) !important;
  border: 1px solid #999 !important;
  border-radius: 3px;
  color: #666 !important;
  cursor: pointer;
  font-weight: normal !important;
  margin-top: 5px;
  padding: 5px !important;
  text-transform: uppercase;
}
.findButton {
  background: none repeat scroll 0 0 #1d6096;
  border: medium none;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  float: right;
  font-weight: bold;
  padding: 8px 21px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="DivGroup">
  <label>Bay Village Branch - <b>Cuyahoga County Public Library</b>

  </label>
  <input type="button" onclick="LoadBranches('CuyahogaCounty')" value="Find Support" class="findButton">
</div>
<div class="DivGroup">
  <label>Bay Village Branch - <b>Cuyahoga County Public Library</b>

  </label>
  <input type="button" onclick="LoadBranches('CuyahogaCounty')" value="Find Support" class="findButton">
</div>
<div class="DivGroup">
  <label>Bay Village Branch - <b>Cuyahoga County Public Library</b>

  </label>
  <input type="button" onclick="LoadBranches('CuyahogaCounty')" value="Find Support" class="findButton">
</div>
<div class="IlsTable" id="ilsList">
  <img src="../../Content/Images/ajax-loader.gif" style="display: none;" id="ajaxLoader">TEXT TEXT TEXT</div>

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

Guide on displaying Adsense ads specifically for mobile devices

Can anyone provide me with a proper method to show/hide my AdSense ads on both mobile and desktop? I am currently using a method that results in 2 console errors. Here is the current approach: We are utilizing two classes, "mobileShow" and "mobileno," t ...

When an HTML table utilizes both rowspan and colspan attributes, it may encounter issues with being overlapped by the

I'm working on a straightforward table that showcases the properties of a data element. Each row will represent an element from the AJAX response in a list format. The table is designed with "rowspan" and "colspan" to expand specific cells. However, ...

Use CSS Grid to anchor the final element to the right side of a horizontal navigation menu

I am facing an issue with my horizontal navigation bar that contains a dynamic number of links. In this specific case, there are 3 links displayed below: My goal is to keep the first two links in their original position and move the third link all the way ...

Managing the response from a dataless AJAX GET request

I find myself stuck on a seemingly simple issue. I am currently working on refining a basic AJAX GET request function that deals with response handling. There is no data being sent out with the request; instead, the data is managed through the GET URL. Whi ...

Prevent the propagation of the ng-click event within a jQuery click event

When a Twitter Bootstrap dropdown is nested inside a tr element, and the tr element is clickable through ng-click, clicking anywhere on the page will collapse the dropdown menu. This behavior is defined in a directive using $document.bind('click' ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

What is the best way to convert a repetitive string into a reusable function?

I am currently retrieving data from an API and I want to display it on my website in a more user-friendly manner. The challenge I'm facing is that the number of variables I need is constantly changing, along with their corresponding values. So, I&apos ...

What is preventing this from retrieving the source code?

I'm trying to retrieve the HTML source code from http://yahoo.com/(index.html) and display it in a dialog box using this code snippet: $.ajax({ url: 'http://yahoo.com', success: function(data) { alert(data); } }); Unfortunately, ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

The issue with Cordova (PhoneGap) is that when you move a video file captured by the camera, the gallery thumbnail

Is there a plugin available for Cordova (Android) that can refresh the gallery? I am currently capturing video using the Cordova plugin cordova-plugin-media-capture, which saves the video to the default sdcard path (gallery). After saving the file, I ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Guide on implementing gradient animation effects in a React component

How can I implement gradient animation effects like this example in a React component using inline CSS? I need to utilize the CSS-based gradient animation effects shown below directly within the React component. Are there any specific packages available ...

Incorporating information into Observable in Angular 2

I'm currently working on loading gifs from the API based on a search parameter in batches of 20. Once I reach the bottom of the page, I need to load another 20. To achieve this, I've implemented observables. However, I'm facing an issue with ...

Exploring ReactJS: Combining JSON data with HTML elements

Recently, I started learning ReactJS. As I'm iterating through JSON data, I realized I need to incorporate some links into it. This is how my JSON data is structured: "text": ["For more information on the functionalities of the platform and services ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

The grid expands to cover the entire width of the browser

Hello everyone, I am a newbie when it comes to JavaScript and CSS. I am in need of a code, whether it be JavaScript or CSS, that will allow me to stretch out a grid layout measuring 5 x 2 along with pictures to completely cover the width of the browser wi ...

Discovering keywords within HTML code and concealing particular content through jQuery

My HTML code snippet is shown below: <div id='p1'> <p>First Paragraph</p> <p>Abbot and Costello - Africa Screams</p> </div> <div id='p2'> <p>Second Paragraph</p> <p>Abbot and ...

Express causing textarea in http form to have empty req.body

Here is a form for users to upload a file and submit text: form(action='/createpost' enctype="multipart/form-data" method='post' id="imgForm") input(type='file' name='imgPath' size = "60") br textarea(na ...

Analyze a designated section and display the top 3 frequently used words

Below is the code snippet provided: <body> <div id="headbox"> <p>Whatever...</p> </div> <div id="feed"> <div> <p>I hate cats</p> </div> <div> <p>I like ...

The backdrop moving in a reverse direction

I recently made a tweak to this code that successfully moves the background in the opposite direction of the scroll. However, there is now an issue where it leaves a blank space at the top, even when the background is set to repeat. The change I made was s ...