3

I have a javascript code that is used for a set of checkboxes used to filter on products displayed in a website.

Now, I want to add a new set of checkboxes. The original set filters by color, this new one will filter by prices.

My question is regarding the javascript part. Is there any way to make it common for both sorting sets of checkboxes? Or should I create a new javascript for this second filter and so on for any new sorting filters I would like to add?

Please see code below.

Thanks!

<script type="text/javascript">
//http://jsbin.com/ujuse/1/edit
$(function() {
    $("input[type='checkbox']").on('change', function() {
        var colors = [];
        $("input[type='checkbox']:checked").each(function() {
            colors.push(this.value);
        });
        if (colors.length) {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php?color=' + colors.join("+"), function() {
            $(".indexMain").fadeIn('slow');
            $(".loadingItems").fadeOut(300);
            });

        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
            $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});

</script>

FIRST SORTING SET:

<div class="bgFilterTitles">
    <h1 class="filterTitles">COLOR</h1>
</div>
<div class="colors">
<?php
include ("connection.php");
$colors = $con -> prepare("SELECT DISTINCT color_base1 FROM item_descr ORDER BY color_base1 ASC");
$colors ->execute();
while ($colorBoxes = $colors->fetch(PDO::FETCH_ASSOC))
{
echo "<input type='checkbox' class='regularCheckbox' name='color[]' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'>   ".$colorBoxes[color_base1]."</font><br />";
}
?>
</div>
</div>

SECOND SORTING SET

<div class="bgFilterTitles">
    <h1 class="filterTitles">PRICE</h1>
</div>
<div class="colors">
<?php
include ("connection.php");
$prices = $con -> prepare("SELECT DISTINCT price FROM item_descr ORDER BY price ASC");
$prices ->execute();
while ($priceSort = $prices->fetch(PDO::FETCH_ASSOC))
{
echo "<input type='checkbox' class='regularCheckbox' name='price[]' value='".$priceSort[price]."' /><font class='similarItemsText'>   ".$priceSort[price]."</font><br />";
}
?>
</div>
</div>

----------- AFTER APPLYING ANSWER:

    <script type="text/javascript">
//http://jsbin.com/ujuse/1/edit
$(function() {
    $("input[type='checkbox']").on('change', function() {
        var boxes = [];
        // You could save a little time and space by doing this:
        var name = this.name;
        // critical change on next line
        $("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
            boxes.push(this.value);
        });
        if (boxes.length) {
            $(".loadingItems").fadeIn(300);
            // Change the name here as well
            $(".indexMain").load('indexMain.php?'+this.name+'=' + boxes.join("+"),
            function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });

        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});
</script>


<?php
function echoCheckboxSet($header, $divClass, $columnName, $setName) {

    include ("connection.php");
$checkboxes = $con -> prepare("SELECT DISTINCT $columnName FROM item_descr ORDER BY $columnName ASC");
$checkboxes->execute();
?>
<div class="bgFilterTitles">
    <h1 class="filterTitles"><?php echo $header;?></h1>
</div>
<div class="<?php echo $divClass; ?>">
<?php
    while ($box = $checkboxes->fetch(PDO::FETCH_ASSOC)):
    $boxColumnName = str_replace('_',' ',$box[$columnName]);
?>
        <input type='checkbox' class='regularCheckbox' name='<?php echo $setName; ?>' value='<?php echo $box[$columnName]; ?>' />
        <font class='similarItemsText'><?php echo $boxColumnName; ?></font>
        <br />
<?php
endwhile;
?>
</div>
<?php
} // end of echoCheckboxSet

// Call our method twice, once for colors and once for prices
echoCheckBoxSet("COLOR", "colors", "color_base1", "color[]");
echoCheckBoxSet("PRICE", "prices", "price", "price[]");
?>

I get to see the checkboxes and click on them but nothing happens.

My indexMain.php retreives the values like this:

$colors = $_GET['color[]'];
echo "TEST".$colors[1];
            $colors = explode(' ', $colors);
            $parameters = join(', ', array_fill(0, count($colors), '?'));
            $items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 IN ({$parameters})");
            $items ->execute($colors);
            $count = $items -> rowCount();

What am I doing wrong???

Thanks!

1
  • Good call, Stan. I wasn't even looking at optimizing the php, heh. Commented Dec 14, 2012 at 17:59

1 Answer 1

3

The jQuery .change() function can be passed an eventObject parameter that has a bunch of data about the event on it. More importantly, inside the .change function, the local variable this is set to the item that the event was fired on. So you should be able to do something like this:

$(function() {
    $("input[type='checkbox']").on('change', function() {
        var boxes = [];
        // You could save a little time and space by doing this:
        var name = this.name;
        // critical change on next line
        $("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
            boxes.push(this.value);
        });
        if (boxes.length) {
            $(".loadingItems").fadeIn(300);
            // Change the name here as well
            $(".indexMain").load('indexMain.php?'+this.name+'=' + boxes.join("+"),
            function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });

        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
                $(".indexMain").fadeIn('slow');
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});

So your change function is now only aggregating together checkbox inputs which share the same name as the one that changed. It looks like this is compatible with your markup. I assumed that your indexMain.php loader script works the same for prices as it does colors. You might need to strip of the square braces ([]) from the end of the name for it to do the right thing. If your behavior needs to be significantly different between colors and prices, you could always just run a switch on the name.

Edit: Taking a crack here at consolidating your php code in a similar way (I think that's what you asked for), here is what I would try.

<?php
function echoCheckboxSet($header, $divClass, $columnName, $setName) {

    include ("connection.php");
    $checkboxes = $con -> prepare("SELECT DISTINCT $columnName FROM item_descr ORDER BY $columnName ASC");
$checkboxes->execute();
?>
<div class="bgFilterTitles">
    <h1 class="filterTitles"><?php echo $header;?></h1>
</div>
<div class="<?php echo $divClass; ?>">
<?php
    while ($box = $colors->fetch(PDO::FETCH_ASSOC)):
?>
        <input type='checkbox' class='regularCheckbox' name='<?php echo $setName'?>' value='<?php echo $box[$columnName]; ?>' />
        <font class='similarItemsText'><?php echo $box[$columnName]; ?></font>
        <br />
<?php
endwhile;
?>
</div>
<?php
} // end of echoCheckboxSet

// Call our method twice, once for colors and once for prices
echoCheckBoxSet("COLOR", "colors", "color_base1", "color[]");
echoCheckBoxSet("PRICE", "prices", "price", "price[]");
?>

A few extra points:

  • It looks like you had a spare </div> in your first example. I removed it.
  • It's unusual to include a connection file more than once per script, and even more unusual to include it from inside a function. I don't know what it's doing, so I didn't refactor it at all; it looks like it is responsible for creating and/or modifying a variable called $con, which is not my favorite way of connecting to a database.
  • The while (expr): to endwhile; syntax is just what I like to use when mixing markup with control structures. You can still use the curly braces to contain the markup itself, if you like.
  • You should really consider doing away with the <font> tag. As of html 4.0, it is deprecated. See html 4 spec, section 15.2.2. Use instead a <span> or a <label> with a for attribute and adding an ID to each of the generated checkbox inputs.
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the answer. It looks good, but cannot get it to work yet. I am using the same code you posted above, however I am not sure about what the variable passed name is: is it boxes? $(".indexMain").load('indexMain.php?'+this.name+=' + boxes.join("+"), function()
Yes, it's boxes. I changed your initial var colors = [] to 'boxes', because the js is supposed to be generic between colors and prices. I see now that I messed up on where the quotes go and wound up with an invalid string. Updating my answer now!
Thanks again! My question is now more on the HTML part. Do I have to update it somehow?
Thanks Patrick. I applied your answer but could not get it to work. Please see the bottom of the original question, where I posted my current code under ------AFTER APPLYING ANSWER
If the markup looks right, then it's probably some javascript error... Can you paste in the generated html (page source) so I can be sure I'm debugging the right thing?
|

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.