Update the button text after it has been clicked

https://i.sstatic.net/QJALK.png

In my code, I have a function that generates bootstrap rows, each containing an input field, textarea, and a remove button.

As I call this function multiple times, I end up with several bootstrap rows. When clicking on the remove button, I change the border color of the input and textarea to indicate that they are not being considered. The remove button functions as a toggle button, adding and removing an error class assigned to the input and textarea.

Now, I want to change the text on the button from 'Remove' to 'Add'. Clicking on the 'Add' button should remove the style from the input and textarea, signaling that their values are now being considered.

function GetDynamicTextBox(value, tag) {
return'<div class="col-lg-4"><input class="form-control" type="text" value="'+tag+'" name="typetag" id="tags" data-role="tagsinput"/></div>'+'' +
    '<div class="col-lg-6"><textarea class="form-control issuetext" name="comment" id="" cols="" rows="">'+value+'</textarea></div>'+
    '<div class="col-lg-2">'+
       '<input type="button" value="Remove" class="remove btn btn-default" /></div>'
}

 $("body").on("click", ".remove", function () {
    $(this).closest('#issue').find('.bootstrap-tagsinput').toggleClass('error')
    $(this).closest('#issue').find('.issuetext').toggleClass('error')


});



<div class='row'id="issue">
   <div class="col-lg-4">
     <input class="form-control" type="text" value="'+tag+'" name="typetag" 
     id="tags" data-role="tagsinput"/></div>
  <div class="col-lg-6">
    <textarea class="form-control issuetext" name="comment" id="" cols="" 
    rows="">'+value+'</textarea></div>
  <div class="col-lg-2">
    <input type="button" value="Remove" class="remove btn btn-default" /></div>
</div>

Answer №1

Simply put, all you need to do is attach a click event listener to the button. When the button is clicked, the event object (e) will be passed to the callback function where you can access the element and update its text using the .innerText property. jQuery is not necessary for this task...

const btn = document.getElementById('testButton');
let clickCount = 0;
btn.addEventListener('click', (e) => {
e.currentTarget.innerText += clickCount++;
});
<button type="text" id="testButton">Initial Value</button>

Answer №2

If you want to dynamically change the text of a button based on a global variable, you can achieve this by adding an event listener to the button.

<button id="toggleButton">Toggle</button>
<script>
var toggle = true;
document.getElementById("toggleButton").addEventListener("click", function(e){
  if(toggle){
      this.textContent = "Off";
      toggle = false;
  } else {
    this.textContent = "On";
    toggle = true;
  }
});
</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

I'm puzzled as to why my JavaScript code only functions correctly when I place it after the HTML, despite having a window.onload event handler in place

Just beginning my journey in a CS class and seeking guidance for my lack of basic knowledge. I've noticed that this JS code only works if placed after the HTML, not within the head tag. Shouldn't window.onload handle that? Can someone clarify wha ...

Error: The variable `$` has not been defined in your Vue.js webpack project

Encountered an error in the browser console while running a Vue.js webpack project. https://i.sstatic.net/s2mEp.png The error occurred due to minimized js files within core.min.js. Specifically, the jQuery minimized js is included inside core.min.js. To ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Using InnerHTML in Javascript within the Quasar/VueJS framework is unsupported

I am looking to dynamically create tables based on the items inside the 'counts' array below. The number of tables and their contents can change. Here is my divContainer, where the innerHTML will be appended: <div id="divContainer" style="pa ...

Streaming data from a third-party API using WebSockets to distribute it to various subclients

In our data-driven application, the backend continuously pulls data from a third-party server and sends it to the frontend clients via websockets. The problem arises when multiple clients connect, resulting in the same data being fetched multiple times unn ...

My function handler is not being triggered when using React's onClientClick

I'm facing an issue with a button component I have, let's refer to it as < MyButton >. <MyButton onClick={this.props.calculate} onClientClick={this.changeColor} > Calculate </MyButton> Whenever I click the button, my cal ...

Exploring the potential of Python loops within Selenium capabilities

My latest project involves scraping data from a search page. Specifically, I need to extract the title, price, and link for each of the 25 results on the page. To achieve this, I'm working with Xpath and utilizing an incremental div number associated ...

Add information from a filled data chart

I'm seeking your assistance with a challenge I am facing. In Form1.php, I have extracted data from the database (flock id, house, breed) which populates one table row. The issue is that this form involves two tables in the database. flock id, house, ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Is it possible to implement a universal margin for the homepage design?

I'm working on a landing page where each section needs the same padding on the left and right but with different background colors. Is there a way to apply this consistent padding to the entire page without affecting the individual section colors? Any ...

Jaws reading out a modal message for accessibility purposes

Hey there! I am currently working on a modal using jQuery UI, but I am facing challenges in making it accessible for JAWS users. Below is the code snippet, and I need the text to be read out when the modal pops up after being triggered by a click on the ma ...

Ways to maintain hover functionality when the submenu is visible

My website features a simple table that displays devices and their characteristics. A condensed version of the table can be found in the link below. import "./styles.css"; import { SubMenu } from "./SubMenu"; const subMenuSlice = <S ...

Adjust the div container to wrap underneath the image if the webpage width decreases

Hello there, I am currently in the process of creating my own portfolio. I have a brief introduction that I would like to display next to an image of myself, with the image positioned on the right side. I have a div called "container" which contains anoth ...

Utilize jQuery to navigate through Bootstrap tabs

I am currently utilizing bootstrap Tabs and am pleased with its functionality. <ul class="nav nav-tabs"> <li class="nav active" id="li_All"><a href="#All" data-toggle="tab">All Exchanges</a></li> <li class="nav" i ...

Utilizing reusable styled components with pseudo elements and advanced logic

How can I make the shared style more dynamic by changing the value of left or width based on a passed value or boolean logic across different components? I prefer not to pass it as a prop in the actual component like <bar left="20" />, but ...

Extract data from JSON using the parse function

After utilizing the function JSON.stringify(), I have obtained this JSON: {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'== ...

Is there a way to customize the look of the close button on a Bootstrap 5 search box?

I am currently in the process of designing a blog template using Bootstrap 5. While working on creating the search box, I encountered a minor issue. The code snippet below has provided me with a small close button: .input-group-append .btn { border-bot ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

The Bootstrap tooltip fails to display the visual style of the tooltip, only showing the data

Following the Bootstrap documentation for tooltips, I have tried to make the tooltip function work properly. However, when I hover over the text, the tooltip text Some tooltip text! only shows up with the alt="" function, but not styled as described in the ...

Exploring Source Map Explorer in Next.js: A Beginner's Guide

Looking for assistance in analyzing the Next.js build using source-map-explorer. Can anyone provide guidance on the script? For React (CRA), the script I use is: "build:analyze": "npm run build && source-map-explorer 'build/sta ...