Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Currently I'm pushing multiple inputs to a array but this is a lot of repeating code, how can I improve this?

 var tickets = [];
    $('.js-ticket').each(function(){
      var ticket = [];
      ticket.push($("input[name='ticket_naam\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_aantal\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_prijs\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_begin_datum\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_begin_tijd\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_eind_datum\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_eind_tijd\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_aanal_max\\[\\]']").map(function(){return $(this).val();}).get());
      ticket.push($("input[name='ticket_aanal_min\\[\\]']").map(function(){return $(this).val();}).get());
      tickets.push(ticket);
    });
  historyVar['tickets'] = tickets;
  });

The Html is reader simple just 9 input fields and i'm running this part on a click of a button

share|improve this question
3  
It's very hard to understand what you're pushing into the array. could you add a full code snippet e.g the html bit and how the array is called – Tolani Jaiye-Tikolo Aug 8 at 21:14
up vote 4 down vote accepted

Try this out:

var tickets = [];
var names = [
    'ticket_naam', 'ticket_aantal', 'ticket_prijs', 'ticket_begin_datum',
    'ticket_begin_tijd', 'ticket_eind_datum', 'ticket_eind_tijd',
    'ticket_aanal_max', 'ticket_aanal_min'
];

$('.js-ticket').each(function() {
    var $ticket = $(this);
    var ticket = $.map(names, function(name) {
        return $ticket.find('input[name="' + name + '\\[\\]"]').val();
    })
    tickets.push(ticket);
});

The one thing I want to point out is I'm searching within each .js-ticket for the inputs, instead of searching globally each time like your function was. I have to imagine this is what you were intending to do in the first place, otherwise the outer each doesn't make much sense.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.