How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility of the content and dynamically change the button text from "show" to "hide" based on user interaction. However, I encountered an issue where all buttons related to the same class would change text without actually being clicked. I need to modify the button text only when it is clicked.

$(document).ready(function() {
  $("body").on("click", ".view", function() {
    $(this).parent().siblings(".card-body").slideToggle(2000, function() {
      if ($(this).css("display") == "none") {
        $(".view").text(' Show');
      } else {
        $(".view").text(' Hide');
      }
      $(".view").toggleClass("fa-eye-slash");
    });
  });

  var i = 1
  $("body").on("click", "input.btn-primary", function() {
    var x = $("textarea").val();
    var title = $("#title").val();
    var article = $('<div class="card" id="article-' + i + '"><div ...
...
...
</script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №1

Modify the function triggered by clicking on the .view element for it to function properly

  $("body").on("click",".view", function(){

    $(this).parent().siblings(".card-body").slideToggle(2000, function(){

        if ($(this).css("display")=="none"){

        $(this).next("div.card-footer").find(".view").text(' Show')

        }else{
        $(this).next("div.card-footer").find(".view").text('Hide');

        }
        $(".view").toggleClass("fa-eye-slash");
    });

});

Answer №2

Here is an alternative method

$(document).ready(function() {
  $("body").on("click", ".view", function() {
    $(this).parent().siblings(".card-body").slideToggle(2000, function() {
      if ($(this).css("display") == "none") {
         $(this).siblings("div.card-footer").find(".view").text(' Show')
        //$(".view").text(' Show');
      } else {
        $(this).siblings("div.card-footer").find(".view").text(' Hide')
        //$(".view").text(' Hide');
      }
      $(".view").toggleClass("fa-eye-slash");
    });
  });

  var i = 1
  $("body").on("click", "input.btn-primary", function() {
    var x = $("textarea").val();
    var title = $("#title").val();
    var article = $('<div class="card" id="article-' + i + '"><div class="card-header"> <div class="card-text text-center"><h5> ' + title + ' </h5></div></div><div class="card-body"><div class="card-text text-justify"><p>' + x + '</p> </div> </div> <div class="card-footer text-right"> <button class="btn btn-primary view fas fa-eye">  Hide</button> <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button> </div> </div>');
    $(".card-columns").append(article);
    i++;
  });
  
  $("body").on("click", ".btn-danger", function() {
    $(this).parents(".card").remove();
  });

  $('input[value="Add Article"]').attr('disabled', true);
  $('textarea').on('keyup', function() {
    var x = $("textarea").val();
    var title = $("#title").val();
    if (x != '' && title != '') {
      $('input[value="Add Article"]').attr('disabled', false);

    } else {
      $('input[value="Add Article"]').attr('disabled', true);
    }
  });
});
.user-name {
  background-color: #d4d4d4;
  line-height: 150px;
}

.comment-form {
  margin: auto;
  width: 70%
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<div class="container">
  <header>
    <div class=" user-name alert text-center mt-3 border-primary">
      User Name /Blog
    </div>
  </header>
  <section class=" row comment-form">
    <div class="card bg-light col-12 p-0 ">
      <div class="card-header bg-primary text-white text-center">
        Add A New Comment
      </div>
      <div class="card-body">
        <form>
          <div class="form-group row">
            <label for="title" class="col-form-label col-sm-2"> Title</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" placeholder="Write Your Title" id="title">
            </div>
          </div>
          <div class="form-group row">
            <label for="comment" class="col-form-label col-sm-2"> Content</label>
            <div class="col-sm-10">
              <textarea class="form-control" rows="3" placeholder="Write Your Content" id="comment"></textarea>
            </div>
          </div>
          <input class="btn btn-primary float-right" value="Add Article">
        </form>
      </div>
    </div>
  </section>
  <section class="mt-3">
    <div class="col-12">
      <div class="card-columns">
        <div class="card" id="article-1">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
        <div class="card" id="article-2">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
        <div class="card" id="article-3">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №3

The problem arises from the fact that in the click handler for the .view class, you are using $('.view') which targets all existing buttons. To resolve this issue, utilize the this keyword to refer specifically to the button that was clicked:

$("body").on("click", ".view", function() {
  var $button = $(this);
  $button.parent().siblings(".card-body").slideToggle(2000, function() {
    $button.text($(this).is(':hidden') ? 'Show' : 'Hide').toggleClass("fa-eye-slash");
  });
});

Answer №4

To begin, assign the button element to a variable and then utilize that variable within the toggle callback function.

$(document).ready(function() {
  $("body").on("click", ".view", function() {
  var btn = $(this);
    $(this).parent().siblings(".card-body").slideToggle(2000, function() {
      if ($(this).css("display") == "none") {
        $(btn).text(' Show');
      } else {
        $(btn).text(' Hide');
      }
      $(btn).toggleClass("fa-eye-slash");
    });
  });

  var i = 1
  $("body").on("click", "input.btn-primary", function() {
    var x = $("textarea").val();
    var title = $("#title").val();
    var article = $('<div class="card" id="article-' + i + '"><div class="card-header"> <div class="card-text text-center"><h5> ' + title + ' </h5></div></div><div class="card-body"><div class="card-text text-justify"><p>' + x + '</p> </div> </div> <div class="card-footer text-right"> <button class="btn btn-primary view fas fa-eye">  Hide</button> <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button> </div> </div>');
    $(".card-columns").append(article);
    i++;
  });
  
  $("body").on("click", ".btn-danger", function() {
    $(this).parents(".card").remove();
  });

  $('input[value="Add Article"]').attr('disabled', true);
  $('textarea').on('keyup', function() {
    var x = $("textarea").val();
    var title = $("#title").val();
    if (x != '' && title != '') {
      $('input[value="Add Article"]').attr('disabled', false);

    } else {
      $('input[value="Add Article"]').attr('disabled', true);
    }
  });
});
.user-name {
  background-color: #d4d4d4;
  line-height: 150px;
}

.comment-form {
  margin: auto;
  width: 70%
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<div class="container">
  <header>
    <div class=" user-name alert text-center mt-3 border-primary">
      User Name /Blog
    </div>
  </header>
  <section class=" row comment-form">
    <div class="card bg-light col-12 p-0 ">
      <div class="card-header bg-primary text-white text-center">
        Add A New Comment
      </div>
      <div class="card-body">
        <form>
          <div class="form-group row">
            <label for="title" class="col-form-label col-sm-2"> Title</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" placeholder="Write Your Title" id="title">
            </div>
          </div>
          <div class="form-group row">
            <label for="comment" class="col-form-label col-sm-2"> Content</label>
            <div class="col-sm-10">
              <textarea class="form-control" rows="3" placeholder="Write Your Content" id="comment"></textarea>
            </div>
          </div>
          <input class="btn btn-primary float-right" value="Add Article">
        </form>
      </div>
    </div>
  </section>
  <section class="mt-3">
    <div class="col-12">
      <div class="card-columns">
        <div class="card" id="article-1">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
        <div class="card" id="article-2">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
        <div class="card" id="article-3">
          <div class="card-header">
            <div class="card-text text-center">
              <h5> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </h5>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text text-justify">
              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
                recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            </div>
          </div>
          <div class="card-footer text-right">
            <button class="btn btn-primary view fas fa-eye">  Hide</button>
            <button class="btn btn-danger"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Propelling Information using the Chakra-UI Drawer Element

I've been exploring the features of the Chakra-UI drawer component and you can find more information about it here. Overall, the functionality aligns with my needs, except for one particular aspect - instead of pushing the content to the side, the dra ...

Utilizing AJAX to dynamically create graphs using Highcharts

I'm having trouble integrating AJAX with highcharts in my project. Here is a snippet of my HTML and javascript code: function test () { var options = { chart : { renderTo : 'container', type : 'spline', ...

Display search bar when scrolling down and hide it when returning to the top of the page

I'm looking to implement a sticky search bar that appears at the top of the page when users scroll down. The landing page already has a search box, so I only want the sticky search bar to show when the original search box is out of view. When the sear ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

ChooseBox (Clavinska) connect interactive created scrollable option lists

Is there a way to connect the created DropDown elements with SelectBox (Clavinska)? Here is an example: $(document).on("mouseenter", function() { $("#countries").selectBox(); }).trigger('mouseenter'); This solution currently works only on mous ...

Changing Settings on the Fly with JQuery

I am facing an issue with a table that has values generated dynamically using PHP, such as id and name attributes (e.g. id="question_". My challenge is how to set an element attribute considering this dynamic nature. For instance, I need to update the tex ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

The propagation of data in Datatables is hindered when using AJAX and JavaScript variables

Currently, I am utilizing datatables to load data through AJAX with custom data. However, when the reference variable in the custom data is changed and the AJAX is reloaded, the value of the custom data does not update. var range=1; var DataTable=$(&ap ...

Is there a way to send a variable to the alert function using $.ajax()?

I need assistance with confirming the deletion of a record. When the user clicks on the button, it should send the value 'Yes' to a $_POST request in PHP for deleting the record. However, instead of working as expected, it is showing me the JavaS ...

Invoking a function in a React component from another component

I am trying to implement a page with the structure shown below: const Upload = (props) => { return ( <BaseLayout> <ToolbarSelection /> <Box> <FileDropArea /> </ ...

Retrieving selected options from a jQuery mobile multiselect for database storage

I'm currently working on extracting values from a select list in a jQuery mobile application. Here's the markup for my select element: <div data-role="fieldcontain"> <label for="stuff" class="select">Stuff:</label ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

How can I position an input element with the class "button" exactly where I need it on the webpage?

I am struggling to position my input (class="button") where I want it to be html: <div id="popup" class="overlay"> <div class="popup"> <a class="close" href="#">×</a> <div id="content"> <select required name="list" ...

Type Error: Issue encountered while resolving module specifier

Upon trying to import the d3.js library in a project that utilizes npm, I encountered the error message: TypeError: Error resolving module specifier: d3. This issue specifically occurred while using Firefox. index.html <!DOCTYPE html> <html lang ...

When using the UI Router, nested views may display double slashes in the URL and redirect back to

I've been working on editing a project to incorporate a root view/state that encapsulates all other views/states within it. Previously, each page functioned as an independent state, making it cumbersome to implement global changes across all states wi ...

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

Datagrid in AngularJS does not update filters upon refresh

Currently, I am attempting to implement name filtering with Angular JS using the following library: https://github.com/angular-data-grid/angular-data-grid.github.io. However, an issue arises when searching as the results do not refresh immediately; only up ...

Placing an image at the forefront of all elements

Recently, I created a horizontal opt-in bar for my Newsletter on my website. Instead of the traditional submit button, I decided to use an image by incorporating some CSS: #mc_embed_signup input.button { background: url(http://urltotheimg.com/image.jpg); ...