1

I'm trying to create a multi dimensional array from form fields that I can loop through with jQuery and perform some calculations on the fly.

The form has an add attendee/remove attendee option and each attendee has 3 inputs so I am trying to create an array like so with the field names

attendees[0][name] = 'Name'
attendees[0][email] = 'Email'
attendees[0][type] = 'Normal'

I am using the following in jQuery to collect this array on the change event of the inputs within the form.

var values = $("input[name='attendees[]']").map(function() {
    return $(this).val();
}).get();
console.log(values);

The alert is just so I know that it is working but as you can see from my fiddle, regardless of what is in the attendee fields the array is always empty.

https://jsfiddle.net/b84s07x4/

0

1 Answer 1

3

You can achieve this quite simply by using map() on the tbody tr elements, instead of the first input in each row, and then using find() to get the required form elements.

You can also simplify the selector by placing a class on the form elements to read, otherwise you have to hack together a selector string using a name attribute which then has to escape the quotes contained within it. That becomes messy quickly.

Try this:

function calculate() {
    var attendees = $('.attendee-table > tbody > tr').map(function() {
        return  {
            name: $(this).find('.attendee-name').val(),
            email: $(this).find('.attendee-email').val(),
            type: $(this).find('.attendee-type').val()
        }
    }).get();
    console.log(attendees);
}

Working example

Sign up to request clarification or add additional context in comments.

3 Comments

This seems to do partly what I require but when removing an attendee the second object is still there. Also the attendee type is not defined on any subsequent attendees bar the first one.
The problem with type was my mistake I missed a quote in the HTML string. Also note that you'll need to call calculate() again in the removal event handler if you want to update the object at that point too. Here's another fiddle with both of those issues addressed: jsfiddle.net/b84s07x4/4
No problem, glad to help. You can do that by clicking the green tick to the left

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.