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

余生长醉 提交于 2019-12-12 02:55:04

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10167098/jquery-reading-an-array-of-form-values-and-displaying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!