supersaiyan
supersaiyan

Reputation: 1730

counter should work on all click and function should be one

i have one counter for script but i want to use the same for counter. i am open for all changes in class and id. here is the code:

$(document).ready(function(){
    $('#target').click(function() {
        $('#output').text(function(i, val) { return val*1+1 });
    });

    $('#targetdown1').click(function() {
        $('#output').text(function(i, val) { return val*1-1 });
    });
    });

here is the example:

http://jsfiddle.net/cY9p7/7/

Upvotes: 2

Views: 49

Answers (2)

Silagy
Silagy

Reputation: 3083

One of the solution i am using not just for your case, is to write the target id of an element i need to update as an attribute on the initiate element

In your case i have added an data attribute on each +/- sign that indicate what is the target element needed to update

HTML Code

<div class="left" id="output1">1</div>
<div class="right">
   <div class="up-arrow" id="target" data-target="output1">+</div>
   <div class="down-arrow" id="targetdown1" data-target="output1">-</div>
</div>

Jquery Code

$(document).ready(function(){
    $('.up-arrow').click(function() {
        var target = $(this).attr("data-target");
        var val =  

        $('#' + target).text(function(i, val) {return val*1+1 });
    });

    $('.down-arrow').click(function() {
        var target = $(this).attr("data-target");
        $('#' + target).text(function(i, val) { 
            if (val == 0)
                return 0;
            return val*1-1 
        });
    });
});

Fiddle Example

Upvotes: 1

adeneo
adeneo

Reputation: 318212

$(document).ready(function () {
    $('.up-arrow, .down-arrow').click(function () {
        var self = this;
        $(this).closest('.counterBox1').find('.left').text(function (i, val) {
            return self.id == 'target' ? (val * 1 + 1) : (val * 1 - 1);
        });
    });
});

FIDDLE

Upvotes: 1

Related Questions