black b
black b

Reputation: 13

How to change label text using jquery

This is div tag

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

Whenever I click on the button, I will add the div tag. when the next div tag is added, it should change the digit in the label text.

For example: In the first div, it should be 1 and in the next div it should be 2.

I am getting the label text using

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

What I want is to change digit in the label text to 2.

I am getting the value but the label value is not getting changed in the html.

How to get the updated label value?

Sorry if there are any mistakes

Upvotes: 1

Views: 3401

Answers (6)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

maybe that one you want DEMO

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

in js

$(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>');

});

Upvotes: 1

Mangesh Parte
Mangesh Parte

Reputation: 2177

You can try this:

$('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));
    });
})

Fiddle Link

Upvotes: 2

Hebrus
Hebrus

Reputation: 133

Since you want to replace the HTML here use

$(this).html("new value");

Upvotes: 0

Sandun Jay
Sandun Jay

Reputation: 502

Hope this will be a help,

var count = 0;

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

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

<button id="btn" type="button">Button</button>

Upvotes: 0

Sarath Kumar
Sarath Kumar

Reputation: 2353

make id for button and trigger the click event to achive it.. try this..

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

here is the fiddle.. http://jsfiddle.net/Sarathv15/0jbq7em3/

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

Something like this:

$('div').find('label').each(function(){
 $(this).text($(this).text().replace(/\d/,2));
});

Upvotes: 0

Related Questions