Bruce
Bruce

Reputation: 1071

Changing values with jQuery

I have the following:

<span class="label-info">3</span>

I have the following jquery

var replaceit = $(this).closest(':has(.label-info)').find('.label-info').text();

The value of the variable is always a single whole number but will not always be 3:

ie: 1, 2, 3, 4, 5.

I have tried this numerous ways and cannot get the value to change. My latest attempt was:

return $(this).closest(':has(.label-info)').html().replace(replaceit, (replaceit - 1)); 

My end result, is to subtract 1 from whatever the current value of "lable-info" is, and switch it with this new result. So a new span based on the value of 3 would become.

<span class="label-info">2</span>

How do I achieve this?

Updated Code for more clarity

html:

<div>
<span class="lable-info">3</span>
</div>

<div>
   <a class="accept_friend">accept</a>
</div>

javascript:

    $(document).on("click", "a.accept_friend", function() { 
        var checkValue = $(this).closest(':has(.name)').find('.name').text();
        var removeit = $(this).closest(':has(.item)').find('.item').fadeOut();
        var replaceit = $(this).closest(':has(.label-info)').find('.label-info').text();
        $.ajax({
            url: '/includes/accept_friend.php',
            type: 'post',
            data: {checkValue},
            success:function(data){
            return removeit;
            $("a.remove_pending").text(function () {
            return ('.label-info').html().replace(replacei, replaceit); 
        });
    }

Notes:

I am not using id. I am using class. There are multiple classes with the same name. So I have to call by closest.

Upvotes: 5

Views: 765

Answers (4)

codelock
codelock

Reputation: 770

Getting a value from a span, subtracting it by 1 and updating the span(using jQuery):

HTML

<span class="label-info">3</span>

jQuery

var n  = $(".label-info").text(),
    n2 = n - 1;
$(".label-info").text(n2);

Hope it helps a bit

Upvotes: 4

Mohammad
Mohammad

Reputation: 21489

You can use .text( function ) to changing text of element to another string.

$(".label-info").text(function(i, text){
    return text - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="label-info">3</span>

Upvotes: 0

Sasikumar
Sasikumar

Reputation: 863

Hope this helps you

var replaceit = $(this).closest(':has(.label-info)').text();
$(this).closest(':has(.label-info)').text(replaceit-1);

Example fiddle https://jsfiddle.net/nzdtnoas/

Upvotes: 0

vishal shah
vishal shah

Reputation: 316

Please try below code

var currentVal = $(this).closest(':has(.label-info)').html();

var newValue = parseInt(currentVal - 1);

return newValue;

Upvotes: 3

Related Questions