10

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>

3 Answers 3

15
    <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>
Sign up to request clarification or add additional context in comments.

1 Comment

Not as elegant as the other solutions, but it works great.
11

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).

Comments

3

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/

3 Comments

@user892134: See Intersellar's comment or the documentation: api.jquery.com/map, and are you trying to get an array or URL string? Your question and code say different things.
an array, which ajax POST to users.php.
@user892134: If you want an array, then your AJAX call would use data: { users: users }, if you're happy with a URL string then do what you're doing now but use Cory's serialize approach.

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.