Elaine Marley
Elaine Marley

Reputation: 2213

Jquery: create array of ids to pass as a get parameter

I have a list of checkboxes, like so:

<input type="checkbox" value="12" name="urssaf-check[]" class="urssaf-check">
<input type="checkbox" value="13" name="urssaf-check[]" class="urssaf-check">

I need to retrieve an array of the ids (values of the checkboxes) selected and pass it as a parameter in an url. So far I have this:

var items = [];
$('.urssaf-check').each(function (key, object) {
    items.push($(this).val());
});

Which gives me:

 ["12", "27", "26", "15", "28", "29", "30", "16", "14", "19", "17", "18", "20", "31", "32", "33", "21", "22", "34", "23", "24", "25"]

So far so good, but now I need this in an url, so that when I do $_GET['ids'] or similar in the controller that will write the content of the page I can see that same array of numbers.

What I try now is this:

 var array = { ids : items };
 var params = $.param( array, true );

And params gives me:

 ids=12&ids=27&ids=26&ids=15&ids=28......

Which in the var_dump of the get parameter will result on me only getting the id of the last item. If I manually add [] after "ids" it will work fine, but I want to know what is the proper way to do this with jQuery.

Edit: I need the url to open in a different window, I'm doing it like this:

 function MM_openBrWindow(theURL,winName,features) { 
        window.open(theURL,winName,features);
 }
 MM_openBrWindow($(this).attr('data-url')+'/?'+params, 'name', "scrollbars=yes,width=1000,height=720");

Upvotes: 1

Views: 2144

Answers (2)

Elaine Marley
Elaine Marley

Reputation: 2213

Well, I'm going to be waiting a few days but so far I did this and it works for me as is. I'm still not happy though and think a better approach to the problem is needed:

            var params = "";
            for (var i = items.length - 1; i > 0; i--) {
                if(i==1){
                    params += 'operations[]='+items[i];
                }else{
                    params += 'operations[]='+items[i]+'&';
                }

            };

Upvotes: 0

Walter Gammarota
Walter Gammarota

Reputation: 136

Maybe you can pass the array directly when you post it to your controller, for example:

$.post( "controller.php", { 'urssaf-check[]': items } );

If you going to send it using post or get, there is no need to parse it.

Upvotes: 1

Related Questions