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!
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.changefunction, the local variablethisis set to the item that the event was fired on. So you should be able to do something like this: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.phploader 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.
A few extra points:
</div>in your first example. I removed it.$con, which is not my favorite way of connecting to a database.while (expr):toendwhile;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.<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 aforattribute and adding an ID to each of the generated checkbox inputs.