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

Issue between Promise and EventEmitter causing race conditions in ExpressJS

Currently, I am working on a NodeJS/Express web application where users can upload files that are then parsed using the connect-busboy module and saved to a database with Sequelize. Once the data is stored, I aim to redirect the user to a specific page. Ho ...

Assigning a specific class to both the first and fourth items

I have a set of 16 elements. They are arranged in 4 rows with 4 items on each row. Is there a way to assign the class '.first' to the first item in each row and '.fourth' to the fourth item in each row? Desired Output: <ul> & ...

I'm having trouble getting EJS files to run JavaScript module scripts

I am facing an issue with my ejs file running on localhost. I am trying to execute functions from other files that are imported with js. In the ejs file, there is a module script tag which successfully executes the code of the file specified in the src att ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

Why does the Next.js GET index request keep fetching multiple times instead of just once?

Currently, I am encountering an issue while working on a tutorial app with Next.js. One of my components is not rendering due to what seems like multiple executions of a simple GET request for an index page. The problem perplexes me, and I need some assist ...

Database query not appearing on node.js route

As a newcomer to javascript and nodejs, I have encountered an issue that I'm hoping to get some clarification on. I am currently working on a simple API and facing difficulties in understanding why a certain behavior is occurring in my code. app.get( ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

Tips for displaying images dynamically in HTML using AngularJS

src={{logo}} var logo = 'localhost:3000/modules/images/default.png' I'm trying to display the image path dynamically, but it's not showing up in the HTML. Do I need to use quotes for src? Can someone please assist me with this issue? ...

Obtain a value from a jQuery POST request

Is it possible to dynamically set the width of a table using a Javascript variable obtained from a jQuery post? $.post("get.php", {this: 'that'}, function(data){ var width = data // for example, '300' ? How can I utilize this variabl ...

Achieving consistent height for Grid items in Material-UI

I'm looking to achieve equal heights for these grid items without distorting them. Here's the current layout: This is how I would like it to look: My challenge is that adjusting the image width manually makes it non-responsive. Since users may ...

The mystery behind React rendering twice, even when React strict mode is disabled

My code is error-free, but React seems to render this component twice for some reason. I can't figure out why. Here is an image showcasing the issue: https://i.stack.imgur.com/hKvug.png Index.js Page : import LandingPage from '../components/Ho ...

Sluggish webpage (Jquery and bootstrap)

I encountered a minor issue... I created a webpage using BOOTSTRAP and included the Nivo slider (jquery) on it. I utilized bootstrap for its basic styling and responsive design capabilities (adaptation for mobile, tablet, etc). However, my webpage perform ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

Removing a property from a JSON object when initiating an Ajax request in JavaScript

Looking for guidance on JavaScript and ajax as a beginner. I have a JSON with an output cell that I want to remove: { "cells": [{ "metadata": { "trusted": true, "collapsed": false }, ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...

Using Ajax, jQuery, and PHP in Internet Explorer 9 is possible, but it may not work in Internet

I am encountering an issue with my jQuery/AJAX script that posts to a php file in order to retrieve XML data. The problem arises when I print the data and notice that all the HTML source code is being returned instead of properly parsed XML, especially in ...

What is the best way to combine two arrays while ensuring the elements of the second array appear before the elements of the first

Is there a way to concatenate two arrays in JavaScript, where the second array appears before the first? For example: const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArr = arr1.concat(arr2); console.log(combinedArr); I am aware that yo ...

Having trouble with selecting JS dropdown options in Python Selenium

My HTML view- Check out the website design HTML code- View the HTML code here When I click on the dropdown arrow, a new code appears - view the code snippet Although my code successfully displays the dropdown options, it does not allow for selecting an ...

Tips for toggling a menu by clicking a link

I have a Navbar component with a hamburger menu. When the hamburger menu is clicked, I want to display the menu component, which is separate. To achieve this, I passed data through props and made it work. Now, I want the menu to close when clicking outsi ...