Search code examples
phpjqueryarraysfacebox

Storing selected checkboxes in array and use it with facebox


I'm having some trouble using jQuery's plugin Facebox to process some data from a form. What I'm trying to accomplish is basically get the values of the number of selected checkboxes into an array and have it available in my popup to process it with PHP. I have something like this on a form page:

form.html

<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />

<input type="button" name="replace" onClick="replace_equip()" />

There are more checkboxes, but I think these are enough to get started.

Here is replace_equip()

function replace_equip() {
  var nArr = new Array();
    $("input:checkbox[name=equip]:checked").each(function() {
  nArr.push($(this).val());
  $.facebox(function() {
    $.ajax({
      data: { name : nArr },
      error: function() {
      $.facebox("err");
      },
      success: function(data) {
      $.facebox(data);
      },
      type: "post",
      url: "test.php"
    });
  });
});
}

I'm trying to save the selected checkboxes into an array, in a way that I can use it for PHP processing in test.php.

I'm just getting started with jquery and javascript in general, so forgive any monster mistakes you may find!


Solution

  • To get started, there are a few stylistic issues with your code. First, you should opt not to use new syntax with Arrays, Objects, etc. Instead, declare your Array with something like var array = [];. Second, you're using an inline onClick, which should be avoided if you're using jQuery already. Instead, use something like $('input[name="replace"]').on('click', function() {...});. You should also consider using camelCase with your functions, and if you like underscores, use them with vars.

    Now onto the meat of your question. I refactored your code like so:

    $('input[name="replace"]').on('click', function() {
        replaceEquip();
    });
    
    function replaceEquip() {
      var array = [];
      $("input:checkbox[name=equip]:checked").each(function() {
        array.push($(this).val());
      });
    
      $.facebox(function() {
        $.ajax({
          type: "POST",
          url: "test.php",
          data: { name : array },
          error: function() {
            $.facebox("err");
          },
          success: function(data) {
            $.facebox(data);
          }
        });
      });
    }
    

    In your PHP code, you would json_decode() this array and work with it how you want. I also moved the type and url params to the top, as your error and success functions may get quite lengthy.

    I would consider reading JavaScript Patterns (at least the Essentials chapter).