Treat
Treat

Reputation: 192

jquery update only number

i have <span class="gramatz">(8)</span> and i would like it to add +1 or take -1 from 8, leaving () untouched, when I click my love button.

$(function() {
    $(".love").click(function() {
        var id = $(this).attr("id");
        var dataString = 'id=' + id;
        var parent = $(this);
        $(this).fadeOut(300);
        $.ajax({
            type: "POST",
            url: "bookmark.php",
            data: dataString,
            cache: false,
            success: function(html) {
                parent.html(html);
                parent.fadeIn(300);
            }
        });
        return false;
    });
});

UPDATE: I forgot I need to decrease the value aswell, check the picture for details: http://img593.imageshack.us/img593/6128/ss20110921031605.png

so if user clicks on +, I need to increase the value, if user clicks on - I need to decrease the number.

so if the icon has + it has this <div class="over_img">&nbsp;</div> and if - it has this <div class="on_img">&nbsp;</div> P.S. plus an minus icons are generated from div background

Upvotes: 2

Views: 248

Answers (3)

Treat
Treat

Reputation: 192

Needed to use .live() to do the trick

Upvotes: 0

Joe
Joe

Reputation: 82584

Only the incrementing code is shown:

$(function() {
    $(".love").click(function() {
        $('.gramatz').text($('.gramatz').text().replace(/(\d+)/, function(str, val) {
            return +val + 1;
        }))
    });
});

Example


EDIT

New Example

$(function() {
    $(".love").click(function() {
        var $class = $(this).attr('class'),
            inc = $class.indexOf('minus') === -1 ? 1: -1;

        $('.gramatz').text($('.gramatz').text().replace(/(-?\d+)/, function(str, val) {
            return +val + inc ;
        }))
    });
});

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219920

$('.gramatz').text(function(i, val){
    return '(' + ( +val.replace('(', '').replace(')', '') + 1) + ')';
});

To break that down:

$('.gramatz').text(function(i, val) {
    var num = val.replace('(', '').replace(')', ''); // "8"
    num = +num; // Convert from string to number
    num = num + 1; // add 1, will now be 9
    return '(' + num + ')'; // "(9)"
});

If you want to use a regex, you can use this:

$('.gramatz').text(function(i, val){
    return '(' + ( +val.replace(/[^\d]/g, '') + 1) + ')';
});

And here's the fiddle: http://jsfiddle.net/gaA2J/


For your particular case, use this:

$('.over_img, .on_img').click(function(){
    var amount = $(this).hasClass('over_img') ? 1 : -1 ;
    $('.gramatz').text(function(i, val){
        return '(' + ( +val.replace(/[^\d]/g, '') + amount) + ')';
    });
});

And here's the fiddle: http://jsfiddle.net/gaA2J/1/

Upvotes: 1

Related Questions