Reputation: 2862
I have a series of buttons (25 of them) used to set the height of something in a web application. I know it's an odd way of doing it, but there's a reason. Each button has an id equivalent to the height it sets, in inches, from 0 to 24, and they all share the HeightButtons class. Here's what I have so far, manually typing it all out:
$('#0').click()(function() {
LiftHeight = 0;
}$('#1').click()(function() {
LiftHeight = 1;
}$('#2').click()(function() {
LiftHeight = 2;
}$('#3').click()(function() {
LiftHeight = 3;
}$('#4').click()(function() {
LiftHeight = 4;
}$('#5').click()(function() {
LiftHeight = 5;
}$('#6').click()(function() {
LiftHeight = 6;
}$('#7').click()(function() {
LiftHeight = 7;
}$('#8').click()(function() {
LiftHeight = 8;
}$('#9').click()(function() {
LiftHeight = 9;
}$('#10').click()(function() {
LiftHeight = 10;
}$('#11').click()(function() {
LiftHeight = 11;
}$('#12').click()(function() {
LiftHeight = 12;
}$('#13').click()(function() {
LiftHeight = 13;
}$('#14').click()(function() {
LiftHeight = 14;
}$('#15').click()(function() {
LiftHeight = 15;
}$('#16').click()(function() {
LiftHeight = 16;
}$('#17').click()(function() {
LiftHeight = 17;
}$('#18').click()(function() {
LiftHeight = 18;
}$('#19').click()(function() {
LiftHeight = 19;
}$('#20').click()(function() {
LiftHeight = 20;
}$('#21').click()(function() {
LiftHeight = 21;
}$('#22').click()(function() {
LiftHeight = 22;
}$('#23').click()(function() {
LiftHeight = 23;
}$('#24').click()(function() {
LiftHeight = 24;
}
Obviously, it's very inefficient. How do I put this into a loop?
Upvotes: 0
Views: 95
Reputation: 1161
Why don't you give them a class also, like this:
$('.dynHeight').on('click', function() {
LiftHeight = this.id;
});
Upvotes: 6
Reputation: 298422
You don't use a loop at all. Give those buttons a class and maybe a data-
attribute:
<button class="height-setter" data-lift-height="12">Click me</button>
And then attach an event handler to them:
var lift_height = 0;
$('.height-setter').click(function() {
lift_height = $(this).data('lift-height');
});
Or, if possible, use their order:
<div class="buttons">
<button>One</button>
...
</div>
And the JS:
var lift_height = 0;
$('.buttons button').click(function() {
lift_height = $(this).index();
});
Upvotes: 2