tags:

views:

211

answers:

3

I am trying to reduce some code here. I will explain how

I have multiple Button controls. I am using the click event for each

$("#B1").click(function() {
                var v1 = "abc";
            });

 $("#B2").click(function() {
                var v1 = "efg";
            });

 $("#B3").click(function() {
                var v1 = "xyz";
            });

I want to remove these 3 clicks event and write a single click event. If the click is from

B1 then v1 should be "abc"; B2 then v1 should be "efg"; B3 then v1 should be "xyz'

How can I write code in the best possible way

+3  A: 

Store the values in a "hash", then reference them from the handler by id.

var vals = { "B1": "abc", "B2" : "efg", "B3" : "xyz" };

$('[id^="B"]').click( function() {
     var v1 = vals[this.id];
     ...      
});
tvanfosson
Thanks..what does '[id^="B"]' mean? Is there any other way also of writing it, since the Buttons may not always be like B1, B2 and so on
[id^="B"] means any element which ID starts with B see the selectors section of the jQuery documentation.
Pim Jager
@Juarte -- there are lot's of ways of writing this. I just keyed off your example. Probably the best way would be to assign a CSS class to the elements that you want to apply the behavior to and use it. Then the selector would look like $('.commonClickable')... -- assuming the class name is "commonClickable".
tvanfosson
tvanfosson..thanks a ton guru! you made this complicated thing look so easy..do you blog anywhere?
@Juarte - just started, farm-fresh-code.blogspot.com
tvanfosson
A: 

If you have a more generic list of names you can use "each" which just loops through you array.

var vals = { "B1": "abc", "B2" : "efg", "B3" : "xyz" };

jQuery.each(vals, function(i, val) {
    $("#" + i).click(function(){
        var v1 = val;
    });
});

As tvanfosson mentioned there are lots of ways to do this. Chances are you may not want to refractor the click events. It's more likely that you need to refractor the code inside of the click event into a more generic function. Make your own function that takes an ID and val and operates on them.

gradbot
+1  A: 

You could also use the data property of the link and then get that in the click event.

$('#B1').data('myKey', 'abc');
$('#B2').data('myKey', 'efg');
$('#B3').data('myKey', 'xyz');
$('.buttons').click(function() {
   var v1 = $(this).data('myKey');
});
bendewey