user892134
user892134

Reputation: 3224

Jquery input array form ajax

How do i get the input array username values in the jQuery variable users?

    <input type='text' name='username[]' class='users' value='test1' />
    <input type='text' name='username[]' class='users' value='test2' />
    <input type='text' name='username[]' class='users' value='test3' />

<div class='submit'>Submit</div>

    <script type="text/javascript">
    $(function() {

        $('.submit').click(function() {

            var users = 
        var dataString = 'users=' + users;

            $.ajax({
            type:'POST',
            url:'users.php',
            data: dataString,
            success: function() {


                }
            });
        });


    });
    </script>

Upvotes: 10

Views: 47008

Answers (3)

Nechehin
Nechehin

Reputation: 1371

    <script>

        $(function() {

            $('.submit').click(function() {

                // Get data as array, ['Jon', 'Mike']
                var users = $('input[name="username[]"]').map(function(){ 
                    return this.value; 
                }).get();

                $.ajax({
                    type: 'POST',
                    url: 'users.php',
                    data: {
                        'username[]': users,
                        // other data
                    },
                    success: function() {

                    }
                });

            });

        });

    </script>

Upvotes: 15

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

Check out jQuery.serialize(). It should give you an array of the usernames.

var users = $('input:text.users').serialize();

You can be however lazy or specific with the selector: .users,input.users,form .users would all work, plus a few more.

For this example:

// users = 
username[]=test1&username[]=test2&username[]=test3

Which, depending on your server-side technology, will come through in the request as an array of strings for the key "username" (PHP, for example).

Upvotes: 11

mu is too short
mu is too short

Reputation: 434615

You can use map to get an array:

// from inside the submit callback
var users = $(this).find('.users').map(function(i, el) {
    return el.value;
});

Demo (run with the console open): http://jsfiddle.net/ambiguous/w2RRW/

Upvotes: 3

Related Questions