Reputation: 192
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"> </div>
and if - it has this <div class="on_img"> </div>
P.S. plus an minus icons are generated from div background
Upvotes: 2
Views: 248
Reputation: 82584
Only the incrementing code is shown:
$(function() {
$(".love").click(function() {
$('.gramatz').text($('.gramatz').text().replace(/(\d+)/, function(str, val) {
return +val + 1;
}))
});
});
$(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
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