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

  • SEARCH
  • Home
  • 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 4586316
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T21:37:18+00:00 2026-05-21T21:37:18+00:00

I have the following code in JQuery, On DOM Ready it runs, its job

  • 0

I have the following code in JQuery, On DOM Ready it runs, its job is to post data to my PHP file, and return the returned data into the specified div. I am using 5 bits of code, most of it is repeating it self over again. I wanted to refactor this somehow, can someone make this code into a couple of lines is possible?

Basically, on change of a select box element, it runs and does the code.

// First Level Categories
    $("#slct_firstCat").live("change", function(){
    $("#div_secondCat").fadeOut();
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_firstCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 1},
        function(data){
            $("#div_secondCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Second Level Categories
    $("#slct_secondCat").live("change", function(){
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_secondCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
        function(data){
            $("#div_thirdCat").fadeIn().html(data);
           });
    // End of Function getCats
    });


// Third Level Categories
    $("#slct_thirdCat").live("change", function(){
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_thirdCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 3},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fourth Level Categories
    $("#slct_fourthCat").live("change", function(){
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fourthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 4},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fifth Level Categories
    $("#slct_fifthCat").live("change", function(){
    $("#successCats").remove();
    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fifthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 5},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

You can see most the code is repeated many times, the only things that change are the element names and the category level in the post action.

I hate having this huge chunk of code in my JS script, used over and over again, surely someone out-there can help reduce this to a few lines or a function if possible?

————————— EDIT —————————

This is the php code that sends the data back from the $.post, if this helps.
Each select box is inside its own div when posted to html, The DIVs are on the html and not ajax’d in.
Basically, I want to navigate down to a category using these select box’s to easily visualize where I am in the category nav. The $data variable, is an object which has an array of the category data requested.
(Sorry Im pressed for time g2g work, else I would have cleaned up the code more)

<?php if (isset($data->CategoryArray->Category->LeafCategory) == 1){ ?>

    <div id='successCats' align='center'>
    <b>Your Selected Category is:</b><br/>
    <select id='selectedCategory' name='selectedCategory' size='1'>
    <option value='<?=$data->CategoryArray->Category->CategoryID."'>".$data->CategoryArray->Category->CategoryName;?></option>
    </select>
    </div>

<?php } else {  ?>
<?php
$catLevel = $_POST['categoryLevel'];
if ($catLevel == 1){
    echo "<select id=\"slct_secondCat\" name=\"slct_secondCat\" size=\"15\">";
} elseif ($catLevel == 2) {
    echo "<select id=\"slct_thirdCat\" name=\"slct_thirdCat\" size=\"15\">";
}
  else if($catLevel == 3){
  echo "<select id=\"slct_fourthCat\" name=\"slct_fourthCat\" size=\"15\">";
} else if($catLevel == 4){
  echo "<select id=\"slct_fifthCat\" name=\"slct_fifthCat\" size=\"15\">";
}

    $cats = array_slice($data->CategoryArray->Category,1);
    foreach ($cats as $cats){
    if ($cats->CategoryID == $cats->CategoryParentID){
    // Do Nothing - Get rid of the first header Cat
    } else {
    $option =  "<option value=\"" . $cats->CategoryID . "\">" . $cats->CategoryName;
    if(!isset($cats->LeafCategory)){
        $option .= " >";
    }

    $option .= "</option>";

    echo $option;
    }
    } // End of For each

} // End of First If Else
?>
<?php echo "</select>"; ?>
  • 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-05-21T21:37:19+00:00Added an answer on May 21, 2026 at 9:37 pm

    But it looks like this block just needs to be turned into a function

    function LevelCategories(levelSelector, levelSelector2) {
        $("#slct_secondCat").live("change", function(){
        $("#div_thirdCat").fadeOut();
        $("#div_fourthCat").fadeOut();
        $("#successCats").remove();
    
        var actionRequested = "AJAX_getCats";
        var url = "index.php";
        var catId = $(levelSelector).val();
    
        $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
            function(data){
                $(levelSelector2).fadeIn().html(data);
               });
        // End of Function getCats
        });
    }
    

    Then just call the function with the correct selectors (I may have those wrong…

    LevelCategories("#slct_firstCat", "#slct_secondCat");
    LevelCategories("#slct_secondCat", "#slct_thirdCat");
    LevelCategories("#slct_thirdCat", "#slct_fourthCat");
    LevelCategories("#slct_fourthCat", "#slct_fourthCat");
    LevelCategories("#slct_fifthCat", "#slct_fourthCat");
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

following code waits till dom ready jQuery(document).ready(function(){ what do i have to write to
I have the following jquery code: jQuery(function(){ jQuery(select#rooms).change(function(){ var options = ''; jQuery.getJSON(/admin/selection.php,{id: jQuery(this).val(),
I have the following jQuery code which runs when I'm clicking an option in
I have the following JQuery code: <script type=text/javascript> $(document).ready(function () { var $containerHeight =
I have the following JQuery code: $(document).ready(function () { var $containerHeight = $(window).height(); if
I have following code <!DOCTYPE html> <html> <head> <title>jQuery goes to DOM-ville</title> <style> #change-me
I have the following code using jQuery Validate. $(#register).validate({ debug: true, errorClass:'error', validClass:'success', errorElement:'span',
I have the following code in a jQuery JavaScript document running on a page
I have the following code for a jquery mobile page. When I run it
I have the following Javascript code (using jQuery): floatUpAndDown(); function floatUpAndDown() { $(#bird).animate({top: '+=30px'},

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.