Haidy
Haidy

Reputation: 257

Making URL out of checkbox values. mvcPattern

I'm facing the following problem. I have a overview of users, and I want a possibility to delete multiple users. So if i check user 1 (userid 1) and user 2 (userid 2) they will both delete.

I want to set this in my URL like: localhost/cms/users/multipledelete/1&2, so with an &amp.

My delete works allready when i put that url hard in my browser. In my javascript i've the following code:

    $('.checkbox').click(function() {
    if($(".checkbox").length == $(".checkbox:checked").length) {
            $("#checkall").prop('checked', this.checked);
        } else {
            $("#checkall").removeAttr("checked");
        }                     
});

And in my index i've set up the follow code:

<td>
<input type="checkbox" class="checkbox" name="check_list[]" value="<?php echo $user->id; ?>"/>
</td>
<td> ....... </td>

And beneath my overview my recyclebin where i want to set the url to: multipledelete/1&2

              <a href="<?php echo $this->url('zfcadmin/user', array('action'=>'multipledelete', 'id'=>'1&2'));?>">
                   <i class="icon-trash"></i>
              </a>

So where 1&2 is, i want the current checked checkboxes. How can i fix this?

Upvotes: 0

Views: 416

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

You'll need to use JavaScript to generate the 1&2 string. Something like this (written in jQuery) should work:

$('.checkbox:checked').map(function() {
    return this.value;
}).get().join('&');

Breaking that down:

  • $('.checkbox:checked') selects the checked checkboxes;
  • .map(function() { return this.value; }) generates a jQuery object containing an array of their values;
  • .get() returns that as an actual array
  • .join('&') returns a string, joining every element of the array with an &

I've created a basic jsFiddle demo so you can see the result of the above.

Now you need to call that when you click on your link (probably best to give it an id or class so you can select it) so that it's dynamic based on what's checked:

$('#anchor-id').click(function(e) {
    e.preventDefault(); // don't follow the link
    var idString = $('.checkbox:checked').map(function() {
        return this.value;
    }).get().join('&');
    window.location.href = this.href + idString;
});

You'd make the href attribute of the <a> tag the static part, so localhost/cms/users/multipledelete/.

Upvotes: 3

Related Questions