MAR
MAR

Reputation: 395

Multiple IDs in a single JavaScript click event

In JavaScript I am using click event to change chart data. Below is a method for click event.

$('#pro1').click(function () {
            chart.series[0].update({
                data: pro1
            });
        });
        $('#pro2').click(function () {
            chart.series[0].update({
                data: pro2
            });
        });
        $('#pro3').click(function () {
            chart.series[0].update({
                data: pro3
            });
        });

I need to minify these three click events in one event, means I want to write one click event which handle the id's. some thing like below code.

$('#pro'+i).click(function () {
chart.series[0].update({
     data: pro+i
});
});


I don't know how to do it exactly. The above code is not correct, it is just my lack of knowledge of JavaScript.

Upvotes: 26

Views: 89718

Answers (7)

Kundan
Kundan

Reputation: 107

Using each function() you can do it

var i =0;
$("#pro"+i+", #pro"+i+", #pro"+i+"").each(function(){
            $(this).on('click', function(){
chart.series[0].update({
     data: pro+i
});

});});

Upvotes: 0

Ram
Ram

Reputation: 144689

I would suggest creating an object and selecting the elements using classes, id of the clicked element retrieves value of the corresponding property of the helper object:

var pros = {
   pro1: '...',
   pro2: '...'
};

$('.pros').click(function () {
    chart.series[0].update({
        data: pros[this.id]
    });
});

Upvotes: 13

Alex K
Alex K

Reputation: 7217

Try this:

var that = this;
$('#pro1,#pro2,#pro3').click(function () {
    chart.series[0].update({
        data: that[$(this).attr('id')];
    });
});

Upvotes: 76

$('#pro1,#pro2,#pro3').click(function () {
    chart.series[0].update({
        data: $(this).attr('id');
    });
});

Updated code

$('#pro1,#pro2,#pro3').click(function () {
    chart.series[0].update({
        data: window[this.id]
    });
});

Upvotes: 11

Grigur
Grigur

Reputation: 465

$("*[id^=pro]").click(function () {
    chart.series[0].update({
         data: $(this).attr('id');
    });
});

Upvotes: 2

Dominic Sore
Dominic Sore

Reputation: 385

You could give all of your elements a class name and use the :eq() selector within jQuery.

Upvotes: 0

Niall Paterson
Niall Paterson

Reputation: 3580

Use a class.

$('.pro').click(function () {
 chart.series[0].update({
   data: $(this).attr('id');
 });
});

And then on each of the #pro1, #pro2, #pro3 elements add a class of 'pro'

Upvotes: 4

Related Questions