Unable to update the contents within a div when clicking on a link

I have a container with a link and some text inside. When the link is clicked, I want to change both the link itself and the content within the container.

There are two different links:

<a href="#" class="add1> Add </a>
<a href="#" class="add2> Subtract </a>

Here is what I need:

1) By default, the "Add" link should be displayed, along with the content inside <div id="addcontent1"> under <div id="answer">.

2) When the user clicks on the "Add" link, the data inside <div id="addcontent2"> should replace the content inside <div id="answer">, and the "Add" link should be replaced by the "Subtract" link.

3) If the user clicks on the "Subtract" link, the original content inside <div id="addcontent1"> should return to <div id="answer">, and the "Subtract" link should switch back to the "Add" link.

Main section:

<div class="change">
    <div class="col-md-2">
        <a href="#" class="add1> Add </a>
    </div>

    <div class="col-md-10">
        <div id="answer">The updated data will display here after clicking one of the above tabs.</div>
    </div>
</div>

Content to be replaced:

<div id="addcontent1">
    Random text will appear here
</div> 

<div id="addcontent2">
    <form action="action_page.php">
        <input type="text" name="name" >    
        <input type="submit" value="Submit">
    </form>
</div>  

Answer №1

This is a type of toggle event. First, create a elements with the content "Subtract" and "Add", then toggle between them. Next, create content objects and store them in a list. Additionally, create two functions for toggling links and contents when clicking on links or specific contents. The data-* attribute can be used to facilitate this process. Here is an example:

Answer №2

$(document).ready(function(){
$("#lnkAdd").click(function(){
    $("#lnkAdd")[0].text="Change";
    $("#content")[0].innerText = "This area is designated for modifications";

});
});

The code provided above can serve as a solution. In this example, I have referenced the jquery-3.1.1.js file. To obtain the jQuery file, please visit http://jquery.com/download/. Once you have downloaded it, simply link the jQuery file to your HTML document and paste the code within the script section.

Answer №3

Is this the desired outcome for you? Feel free to make any changes or additions as needed.

$("body").on("click", "a.add", function(){
    $(this).removeClass('add').addClass('subtract').html('<h4>Subtract</h4>')
    $(this).parent().next('div').text('This section is for subtract content')
});

$("body").on("click", "a.subtract", function(){
    $(this).removeClass('subtract').addClass('add').html('<h4>Add</h4>')
    $(this).parent().next('div').text('This section is for add content')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="change">
   <div class="col-md-2">
      <a href="#" class="add"><h4> Add </h4></a>
   </div>

   <div class="col-md-10">
       This section is for add content
   </div>
</div>

Answer №4

One approach could be to utilize jQuery's append method...

similar to the following example:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

  <div class="update">
   <div class="col-md-2">
    <a href="#" class="modify"> Modify </a>
  </div>

  <div class="col-md-10 update-content">
   This area is reserved for content updates
 </div>
</div>
<script>
  $(document).ready(function(){
    $(".modify").click(function(){
      if ($(".modify").text() == "Adjust"){
       $(".modify").text("Modify");
       $(".update-content").text("This area is reserved for content updates");
     }else{
       $(".modify").text("Adjust");
       $(".update-content").text("This area is reserved for adjustment content");
     }
   });
  });
</script>
</body>
</html>

Answer №5

Here is a simple solution that requires minimal changes to your original code

$(document).ready(function(){

    $('.change a').on('click', function(e){
        e.preventDefault();
        
        if( !$(this).hasClass('subtract') ){
        $(this).addClass('subtract').text('Subtract');
        $(this).parents('.change').find('div').eq(-1).text("This section is for subtract content");
        }else{
        $(this).removeClass('subtract').text('Add');
        $(this).parents('.change').find('div').eq(-1).text("This section is for add content");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="change">
   <div class="col-md-2">
      <a href="#"> Add </a>
   </div>

   <div class="col-md-10">
       This section is for add content
   </div>
</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

How come my ejs files are all affected by the same stylesheet?

Currently, I am in the process of developing a nodeJS application utilizing Express, MongoDB, and EJS template view engine. The server.js file has been successfully created to establish the server. In addition, a separate header.ejs file has been implement ...

Tips for utilizing jQuery to identify an image that is being hovered on?

Concept My goal is to create an effect where a user hovers over an image and a transparent overlay div appears on top of it. This overlay div starts with a height of 0px and should increase to half of the image height upon hover. The hover functionality ...

Adding conditional parameters to an object in JavaScript is a powerful way to control

In my current code, I am attempting to add the passStatus property to an object only if it has a value, otherwise leaving it out. I looked into this solution - In Javascript, how to conditionally add a member to an object? However, it appears that I may ...

Using routes with optional parameters can inhibit the loading of other routes

In my Node.js app based on Express, I have implemented three different routes. app.get('/', function (req, res) { // }) app.get('/findOne', function (req, res) { // }) app.get('/getFour', function (req, res) { // }) Init ...

After clicking, I would like the text from the list item to have a style of "background-color: aqua" when displayed in the textarea

Is there a way to apply a highlight with a style of "background-color: aqua" in the textarea only to the word selected from the list above after clicking on it? See below for my HTML: <head> <script src="https://ajax.googleapis.com/ajax/libs/ ...

Vue.js: Dynamically display buttons in the navigation bar depending on the user's login status through Vuex Store state

I am currently in the process of creating a navigation bar that displays different buttons based on whether the user is logged in or not. To achieve this, I am utilizing Vuex and localStorage to manage the state. My goal is to develop a dynamic menu using ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

Adjust the value of an option within a select input using URL parameters

With regards to this page: I am in the process of developing a script that can extract a parameter from the URL to dynamically modify the select option, thus changing which vehicle is showcased alongside the Honda on the chart. I experimented with the fo ...

Navigating through the realm of Android development entails understanding how to manage a multi-object function in JavaScript when using

In order to load an HTML page using the webview component and handle its functions, I am faced with a challenge. The HTML page contains a multi-object named (webkit.messageHandlers.adClicked). How can I utilize the webView.addJavascriptInterface() functi ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

Tips for adjusting the content direction of a Popover

I am currently working on a component that includes the following code: import { Popover, PopoverTrigger, PopoverContent, PopoverBody, Portal, Button, } from "@chakra-ui/react"; import { ReactNode } from "react"; import { Co ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

Saving an image source to your local disk: A step-by-step guide

I have included an image code in my HTML file: <span style="display:inline"> <img NAME="anImage" height="250" src="https://chart.googleapis.com/chart?" alt=""> </span> Now, I would like to enhance this by adding a button. ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

Varied quantities of columns in each row

Correct LayoutI am looking to customize the layout by displaying the first two rows with 3 columns each, the third row with 5 columns, and the fourth row with 4 columns, using CSS modifications only. CSS ul { columns: 3; } HTML <ul class="list&qu ...

`Exit function in Vue.js: A step-by-step guide`

Here is a code snippet in vue.js which includes an async function: async up(id, point){ this.change = true const pId = id + '-' + firebase.auth().currentUser.uid db.collection('answer').d ...

Getting the correct JSON field value from a JavaScript Promise object in the right way

Trying to fetch data in JSON format from a URL, I encountered an issue where the value of responseData.title differed between two calls made within the second .then() function below: var getTitleForId = async function(id) { if (!id) return fal ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

Creating a stroke in SVG using JavaScript

I created a code that inserts a line into my svg page when I press a button Here is the html snippet: <body> <svg width="500" height="400"> </svg> <button id="btn1">Append text</button> </body> Below is the script us ...

The background color of the div or section is stubbornly refusing to change, no matter how much I tweak it

.forBackground { background-color: white; } .kontaktUndMapContainer { width: 100%; padding: 20px; color: gray; text-align: center; } .überschriftKontakt { margin-bottom: 20px; } .überschriftKontakt2 { margin-top: 20px; margin-bottom: 2 ...