Easy Steps to Update Label Text with jQuery

This is a div element

<div>
    <label>some text 1</label>
    <label>another text 1</label>
</div>
<button>button</button>

Each time the button is clicked, a new div tag will be added. The digit in the label text of each new div should increment.

For example: The first div should have 1, the second div should have 2, and so on.

I am currently retrieving the label text using

var labelValue = $('div').find('label').map(function() {
   return $(this).text().replace(/\d/,2);
}).get();

My goal is to update the digit in the label text to 2.

Although I can fetch the value, the label text in the HTML remains unchanged.

How can I display the updated label value?

Apologies for any errors in my code.

Answer №1

Give this a shot:

$('button').on('click', function(e) {
    $('div:eq(0)').clone().insertAfter('div:last').find('label').filter(function(e) {
        $(this).text($(this).text().replace(/\d/, $("div").length));
    });
})

Try it out on Fiddle

Answer №2

Perhaps this is the solution you are looking for: VIEW DEMO

<div id="show_divz">
    <div id="div_1">
        <label>some text 1</label>
        <label>another text 1</label>
    </div>
</div>
<button>button</button>

This code should be implemented in JavaScript:

$(document).on('click','button',function(){
    var getId = $(this).prev().find('div').last().attr('id');
    getId = getId.split('_');
    $("#show_divz").append('<div id="div_'+(parseInt(getId[1])+1)+'"><label>some text '+(parseInt(getId[1])+1)+'</label><label>another text '+(parseInt(getId[1])+1)+'</label> </div>');
});

Answer №3

Here's an example:

$('section').find('span').each(function(){
 $(this).text($(this).text().replace(/\d/,8));
});

Answer №4

To achieve this, create an id for the button and trigger the click event. Give it a shot!

<div>
    <label>text 1 here</label>
    <label>more text 1</label>
</div>
<button id="btn">Click me!</button>
<script> 
    $('#btn').click(function(){
        $('div').find('label').each(function(){
            $(this).text($(this).text().replace(/\d/,2));
        }); 
    }); 
</script>

Check out the fiddle here: http://jsfiddle.net/UniqueUsername123/samplefiddle/

Answer №5

I trust this information proves useful,

let counter = 0;

$("#btn").click(function() {
    counter++;
    $("#lbl").html(counter);
}

</script>
<div><label id="lbl">1</label></div>

<button id="btn" type="button">Click Here</button>

Answer №6

If you are looking to update the HTML content in this section, you can do so by using the following code:

$(this).html("updated content");

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

What is the best way to generate an array containing multiple arrays, each filled with dynamic Divs?

I have the following code that displays a Div when the user clicks on the Add button. For example, if the user clicks the Add button 5 times, then 5 will be displayed with the same controls/inputs under default. html <div ng-repeat="st in stu"> ...

Creating a chat interface with chat bubbles in React JS can be done by implementing components such as Message

Having some JSON data stored in dummyData, I am seeking guidance on how to position chat bubbles on the left and right based on the direction. My framework of choice is Material UI along with the context API. The attached image serves as a visual reference ...

Styling a half circle in React Native

Despite my efforts, I have not been able to find anything quite like this: example Could anyone provide guidance on implementing this with react? ...

Is there a way to make the first Image Element within the div automatically clickable?

Is there a way to set the first image in a div as the default clicked element? I have a div with multiple images and I want the first one to be clicked by default. This is part of a React functional component that serves as a view. <div className=&quo ...

"Event triggered upon completion of jqgrid data retrieval from dataurl

Utilizing jQuery to fetch a list of suppliers based on a part number, I aim to load additional data concerning the supplier/part number combination once the edit form is displayed. The issue arises from the fact that the dataurl method, which is invoked in ...

What steps can I take to ensure that the @blur event functions correctly in Nuxtjs?

I'm attempting to implement a function that validates an input field when it loses focus in nuxtjs. Strangely, the function doesn't trigger when I move out of the input field, but does trigger when I move into another input field and start typing ...

Creating a grid in JavaScript using a formula

I'm looking to create a grid of objects using JavaScript. Unfortunately, I can't remember the formula and I haven't been able to find it online: var width = 113; var height = 113; var col = 10; ...

My Node.js script is encountering the issue of HTML entities being inserted into the code

I'm encountering a challenge with my Node.js script where I am consistently receiving the error message: SyntaxError: Invalid or unexpected token. The detailed error output is as follows: file:///home/username/www/pathtomyapp/js/folder/file.js:1 conso ...

Animating ng-switch transitions within a div element

Utilizing bootstrap 3 panel along with ng-switch for a sliding animation: Check out the Plunker here I am facing an issue where the animation extends past the borders of the panel instead of staying within it. How can I fix this in my Plunker? The desire ...

Include a pop-up with an image within a table - Shiny

I have a situation where I need to display images and metrics in a compact table. The challenge is to show the images in a small size within the table, but allow users to hover over them for a larger view using a popover feature. While I managed to resize ...

Reorder the position of an item within an array

I have an XML data source that provides all the information needed for my Vue app. Everything is working smoothly except for one specific value. The issue lies in retrieving a date from an element, which is currently formatted as: ['2022-10-25'] ...

Loading numerous scripts utilizing jsdom.jQueryify

Can anyone help with loading an extra .js script using the code below? ["http://code.jquery.com/jquery-2.1.1.js","http://someotrherscript.js"] I am attempting to use jsdom.jQueryify like this: jsdom.jQueryify(window, ["http://code.jquery.com/jq ...

Why am I encountering http://localhost:3000/api/auth/error?error=AccessDenied when implementing Google signin in my Next.js application?

Can someone please assist me in resolving an issue I am facing with my NextJs application using Google signin? Whenever I try to sign in, I get the error message "http://localhost:3000/api/auth/error?error=AccessDenied". Why is this happening? Here is a ...

Retrieve image file from computer's hard drive

I have the following HTML Tags: <input id="bigPicture" name="bigPicture" type="file" value=""> <img src="test.png" id="test1"> User select file and I want to preview this file inside ...

A step-by-step guide on how to use ajax and node to save a file onto

Trying to save a file to the user's disk when they click on it using this ajax code: $('.cv_download').on('click',function(){ var fileName = $(this).text(); console.log(fileName) var temp = {"file" : fileN ...

Encountering issues with integrating NPM package into Meteor.js

Having installed both the meteor-npm package and the crypto npm package, I encountered some issues while using it in Meteor. npm: updating npm dependencies -- crypto Despite seeing this output in the console, when trying to use the npm package on the ser ...

Angular CSS: ng-style applied to only one side, the other remains unaffected

I am working on an Angular application that requires a split screen with two halves, each displaying the same array values. The width and height values are set using a service and accessed by a controller. The style is applied using ng-style in the DOM. Ho ...

Closing a dropdown on outside click in NEXT.JS can be done by adding an event

Currently, I am in the process of developing an ecommerce platform that features a search input with results displayed in a dropdown. The search functionality is working as intended, but now I would like to implement a feature where the dropdown closes whe ...

File Upload Error||The file type you are trying to upload is not permitted

Encountering issues when trying to store a video on the server despite modifying all possible types in mimes.php. Here is my code: Controller public function frontsliderAdd() { if ($this->session->userdata('admin_logged_in') != TRU ...

Developing a website using custom modules in Node.js and Express framework

I am currently encountering an issue when using a custom module within one of my route functions in Express with node. Below is my current setup: In the app.js file, I require the module as follows: c_controller = require( './core/c_controller' ...