Multiple select menus onChange update specific select menu by name through ajax call

I have a form which allows you to update a products main category and sub category through select menus. The options in the sub category select menu change depending on the main category selected through a ajax db call. I can get this to work perfectly through the below JQuery script if the form contains only one product. However if the form contains multiple products. every products sub category select menu also changes to the same set of options

for example: on a single Product which is say orange juice Main categories = Fruit, salad, beverages If I select beverages for example the sub category menu options correctly updates to: Glass, can, carton, bottle That’s all good

however if the form contains multiple products all their sub category options also update to: Glass, can, carton, bottle

I know this is because the dynamically generated select name attribute for each sub category uses the same name (see example html form below).

The form and products are generated dynamically through PHP and the number of products can vary from 1 to say whatever… So my question is how do I change the below script to update the correct products sub category menu options without effecting the other products sub category menu options?

$(document).ready(function() {
  $("select[name='Category']").change(function() {
    var CategoryID = $("select[name='Category'] option:selected").val();
    var SubCategoryID = $("select[name='SubCategory'] option:selected").val();    

    if (CategoryID) {     
              $.ajax({
                url: '/__Dependencies/JQuery/GetSubCategories2.script.php',
                type: 'POST',
                data: {Category: CategoryID, SubCategory: SubCategoryID},
                cache: false
            }).done(function(data) {
                $("select[name='SubCategory']").html(data);
                });
                }
    });

Revised JQuery to the below:

$(document).ready(function () {
  $("select[name='Category']").change(function () {
     const SelectorName = $(this);
    const Category = $(this).val();
    const $SubCategory = $(this).next();

    // Check that a selector with the name "Category" exists in the html document
    if (!SelectorName) {
      alert("The selector name does not exist in the HTML document!");
    }

    // Validate that field is not empty before AJAX call
    if ($.trim($("Category")) != '') {
      $.ajax({
        type: 'POST',
        url: '/__Dependencies/JQuery/GetSubCat.script.php',
        data: {
          Category: Category,
        },
        cache: false
      }).done(function(data) {
        $SubCategory.html(data);
      });
    }
    });
});

<!doctype html>
<html>
<head>
</head>
<body>

    <form name="updateProducts" action="file.php" method="post">
        <ul>
            <li><label for="Category">Cocoa Cola 330ml</label>
                <div>
                    <select name="Category" id="Category">
                        <option value="8">Bakery</option>
                        <option value="11" selected="selected">Beverages</option>
                        <option value="9">Meat</option>
                        <option value="10">Poultry</option>
                        <option value="1">Vegetables</option>
                    </select>
                    <select name="SubCategory" id="SubCategory">
                        <option value="7">Cans</option>
                        <option value="8">Bottles</option>
                        <option value="2">cartons</option>
                        <option value="4">Glass</option>
                    </select>
                    <button type="submit" name="Submit" value="Update">update</button>
                </div></li>

            <li><label for="Category">Cocoa Cola 500ml</label>
                <div>
                    <select name="Category" id="Category">
                        <option value="8">Bakery</option>
                        <option value="11" selected="selected">Beverages</option>
                        <option value="9">Meat</option>
                        <option value="10">Poultry</option>
                        <option value="1">Vegetables</option>
                    </select>
                    <select name="SubCategory" id="SubCategory">
                        <option value="7">Cans</option>
                        <option value="8">Bottles</option>
                        <option value="2">cartons</option>
                        <option value="4">Glass</option>
                    </select>
                    <button type="submit" name="Submit" value="Update">update</button>
                </div></li>
        </ul>
    </form>
</body>
</html>
});

Answer

  1. UNIQUE IDs (or don’t use IDs)
  2. This will update ALL subcats on the page $("select[name='SubCategory']").html(data);
  3. Use relative addressing

I would personally also add a “please select” option 0 and test that the val was empty before ajaxing

Have a look at this first

$(function() {
  $(".Category]").on("change", function() {
    const category = $(this).val();
    const $subCategorySel = $(this).next(); // sibling element, here the related SubCategory select

    if (category) {
      $.ajax({
        url: '/__Dependencies/JQuery/GetSubCategories2.script.php',
        type: 'POST',
        data: {
          Category: category,
        },
        cache: false
      }).done(function(data) {
        $subCategorySel.html(data);
      });
    }
  });
});
<form name="updateProducts" action="file.php" method="post">
  <ul>
    <li><label for="Category">Cocoa Cola 330ml</label>
      <div>
        <select name="Category" class="Category">
          <option value="8">Bakery</option>
          <option value="11" selected="selected">Beverages</option>
          <option value="9">Meat</option>
          <option value="10">Poultry</option>
          <option value="1">Vegetables</option>
        </select>
        <select name="SubCategory" class="SubCategory">
          <option value="7">Cans</option>
          <option value="8">Bottles</option>
          <option value="2">cartons</option>
          <option value="4">Glass</option>
        </select>
        <button type="submit" name="Submit" value="Update">update</button>
      </div>
    </li>

    <li><label for="Category">Cocoa Cola 500ml</label>
      <div>
        <select name="Category" class="Category">
          <option value="8">Bakery</option>
          <option value="11" selected="selected">Beverages</option>
          <option value="9">Meat</option>
          <option value="10">Poultry</option>
          <option value="1">Vegetables</option>
        </select>
        <select name="SubCategory" class="SubCategory">
          <option value="7">Cans</option>
          <option value="8">Bottles</option>
          <option value="2">cartons</option>
          <option value="4">Glass</option>
        </select>
        <button type="submit" name="Submit" value="Update">update</button>
      </div>
    </li>
  </ul>
</form>