John
John

Reputation: 10146

JQuery - Reading an array of form values and displaying it?

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?

Upvotes: 0

Views: 3482

Answers (2)

Lazerblade
Lazerblade

Reputation: 1127

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.

Upvotes: 0

user188654
user188654

Reputation:

$('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());
});

Upvotes: 4

Related Questions