2

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

4 Answers 4

7

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];
     ...      
});
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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..thanks a ton guru! you made this complicated thing look so easy..do you blog anywhere?
3

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');
});

Comments

0

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.

Comments

0

You can add data attributes like data-customAttr="true" in you controls. And then handle the event like this,

$('[data-customAttr^="true"]').click( function() {
 var v1 = vals[this.id];
});     

Using data- attributes is standard and all such attribute can be accessed through jquery's .data() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.