Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8989697
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T22:19:31+00:00 2026-06-15T22:19:31+00:00

I have a javascript code that is used for a set of checkboxes used

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T22:19:32+00:00Added an answer on June 15, 2026 at 10:19 pm

    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.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some JavaScript that is being used to open a new window and
I have some javascript code that is used in a few different pages in
I have seen Javascript code that uses parenthesis immediately after a function's closing curly
I have a javascript code that have span tag and inside the span tag
I have some Javascript code that will programmatically register an COM interop assembly by
I have some JavaScript code that works in IE containing the following: myElement.innerText =
I have some javascript code that creates an img tag with a mouseover callback,
I have some Javascript code that creates 2 arrays: One for Product Category and
I have some javascript code that saves a cookie. However, if after saving the
I have this JavaScript code that creates a table, and puts in the rows

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.