0

I have a form and in the form I'm appending hidden values dynamically via JQuery and these hidden values look like this:

<input type="hidden" name="times[]" value="{'time': '5:00pm','date': 'april 15th'}" />
<input type="hidden" name="times[]" value="{'time': '6:00pm','date': 'april 16th'}" />
<input type="hidden" name="times[]" value="{'time': '7:00pm','date': 'april 17th'}" />

Using JQuery how can I iterate through the times[] array and output each value so the person can see all the values they have been adding in the form prior to submitting the form?

John
  • 9,840
  • 26
  • 91
  • 137

2 Answers2

4
$('input[name="times[]"]').each(function(){
    console.log($(this).val()); // Or anything you like.
});

Or you could use an array to push all fetched values in it. What are you going to do with the values is entirely up to you.

var values = [];
$('input[name="times[]"]').each(function(){
    values.push($(this).val());
});
0

First off you'll need to have unique names for each of the hidden fields. I'd suggest times[0], times[1], etc...

To iterate through them, also give them all the same class, and use each.

for (var i = 5; i > 0; i--) {
    $('<input type="hidden" name="times[' + i + ']" class="times" value="{your array values here}" />').appendto('.myform');
}

Then after the values are set:

var times = '';
$('.times').each(function() {
    times = times + $(this).val() + '<br />';
});
$('.values').html(times);

where values is the container that you use to show the values.

Lazerblade
  • 1,119
  • 7
  • 17