tags:

views:

61

answers:

2

Is there a better, more efficient way to write this code? It's a make shift drop down menu that allows user to RSVP for multiple people. Sorry, it's kind of a mess, but I think what I'm doing is clear. If not, I'm at my computer and will respond quickly with more info need be.

 //There's got to be a better way to do this
 $('#guest_num_1').click( function() {
 $('#num_guests a#quant_guests').html("1")
 $('.guest_name_2, .guest_name_3, .guest_name_4, .guest_name_5, .guest_name_6 ').hide()
 });

 $('#guest_num_2').click( function() {
 $('#num_guests a#quant_guests').html("2")
 $('.guest_name_2').fadeIn()
 $('.guest_name_3, .guest_name_4, .guest_name_5, .guest_name_6').hide()
 });

 $('#guest_num_3').click( function() {
 $('#num_guests a#quant_guests').html("3")
 $('.guest_name_2, .guest_name_3').fadeIn()
 $('.guest_name_4, .guest_name_5, .guest_name_6').hide()
 });

 $('#guest_num_4').click( function() {
 $('#num_guests a#quant_guests').html("4")
 $('.guest_name_2, .guest_name_3, .guest_name_4').fadeIn()
 $('.guest_name_5, .guest_name_6').hide()
 });

 $('#guest_num_5').click( function() {
 $('#num_guests a#quant_guests').html("5")
 $('.guest_name_2, .guest_name_3, .guest_name_4, .guest_name_5').fadeIn()
 $('.guest_name_6').hide()
 });

 $('#guest_num_6').click( function() {
 $('#num_guests a#quant_guests').html("6")
 $('.guest_name_2, .guest_name_3, .guest_name_4, .guest_name_5, .guest_name_6').fadeIn()
 });
+3  A: 
$('.guest_num').click(function() {
  var n = $(this).attr('href').split('#')[1];
  $('#num_guests a#quant_guests').html(n);
  var curr = $('.guest_name_' + n);
  curr.prevAll().fadeIn();
  curr.fadeIn();
  curr.nextAll().hide();
  return false;
});

On the HTML side:

<a class="guest_num" href="#1">...</a>
Fábio Batista
+1 I was in the middle of writing out pretty much this exact code. :]
matt lohkamp
Looks like I'm a faster typer ;) It's still pretty ugly though...
Fábio Batista
Thank you very much guys!
adamwstl
@ghoppe `curr.prevAll()` does not include `curr`. Check: http://api.jquery.com/prevAll/
Fábio Batista
@Fábio thanks I was confused in my testing as I chained the `curr.fadeIn().prevAll().fadeIn();` to save a line. oops. I'll delete my misguided comment.
ghoppe
OK, a better way to save a line: `curr.prevAll().andSelf().fadeIn();`
ghoppe
A: 

use a loop and store this "guest_num_1" and for every eteration change the '1' with the loop index

Yassir