Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple controls with single event using jquery

Tags:

jquery

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


1 Answers

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];
     ...      
});
like image 187
tvanfosson Avatar answered Dec 10 '25 02:12

tvanfosson