Home > Enterprise >  jQuery: hiding form elements doesn't work
jQuery: hiding form elements doesn't work

Time:04-11

I have this form where I want to hide specific parts of it based on the subsubcategory_id selected but I can't seem to make it work.

I have a script that changes subcategory based on category selected and another one that changes subsubcategory based on subcategory selected.

The script for hiding parts of the form works but only for category that comes from the DB and not for subsubcategory that is affected by the first script. The value of the option element in the select just seems to register as empty for the 2nd script. What should I do to fix it?

<script type="text/javascript">
        $(document).ready(function() {
          
            $('select[name="category_id"]').on('change', function() {
                var category_id = $(this).val();

                if (category_id) {
                    $.ajax({
                        url: "{{ url('/category/subcategory/subsubcategory') }}/"   category_id,
                        type: "GET",
                        dataType: "json",

                        success: function(data) {
                            $('select[name="subsubcategory_id"]').html('');
                            var d = $('select[name="subcategory_id"]').empty();
                            $.each(data, function(key, value) {
                                $('select[name="subcategory_id"]').append(
                                    '<option value="'   value.id   '">'   value
                                    .subcategory_name   '</option>');
                            });
                        },
                    });
                } else {
                    alert('danger');
                }
            });

            $('select[name="subcategory_id"]').on('change', function() {
                var subcategory_id = $(this).val();
       
                if (subcategory_id) {
                    $.ajax({
                        url: "{{ url('/category/subcategory/subsubcategory/product') }}/"  
                            subcategory_id,
                        type: "GET",
                        dataType: "json",

                        success: function(data) {
                            var d = $('select[name="subsubcategory_id"]').empty();
                            $.each(data, function(key, value) {
                                $('select[name="subsubcategory_id"]').append(
                                    '<option value="'   value.id   '">'   value
                                    .subsubcategory_name   '</option>');
                            });
                        },
                    });
                } else {
                    alert('danger');
                }
            });
        });
    </script>
    
    // script to hide parts of the form
    
    <script>
        $(document).ready(function() {
            $('#fieldLaptop').hide();
            $('#fieldTablet').hide();
            $('#fieldPhone').hide();

            $("#test").change(function() {
                var subsubcategory_id = $(this).val();
                if (subsubcategory_id == 1) {
                    $('#fieldLaptop').show();
                    $('#fieldTablet').hide();
                    $('#fieldPhone').hide();
                } else if (subsubcategory_id == 2) {
                    $('#fieldLaptop').hide();
                    $('#fieldTablet').show();
                    $('#fieldPhone').hide();
                } else if (subsubcategory_id == 3) {
                    $('#fieldLaptop').hide();
                    $('#fieldTablet').hide();
                    $('#fieldPhone').show();
                } else {
                    $('#fieldLaptop').hide();
                    $('#fieldTablet').hide();
                    $('#fieldPhone').hide();
                }
            });
        });
        $("#test").trigger("change");
    </script>
 <form method="post" action="{{ route('product-store') }}" enctype="multipart/form-data">
                    @csrf
                    <div >

                        <div >
                            <label for="formLayoutUsername3">Brand</label>
                            <select name="brand_id" >
                                <option value="" selected="" disabled="">Brand</option>
                               
                                    <option value="{{ $brand->id }}">
                                        {{ $brand->brand_name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('brand_id')
                                <span ><strong>{{ $message }}</strong></span>
                            @enderror
                            </select>
                        </div>

                        <div >
                            <label for="formLayoutEmail3">Categorie</label>
                            <select name="category_id" >
                                <option value="" selected="" disabled="">Category
                                </option>
                          
                                    <option value="{{ $category->id }}">
                                        {{ $category->category_name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('category_id')
                                <span ><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>

                        <div >
                            <label for="formLayoutPassword3">SubCategory</label>
                            <select name="subcategory_id" >
                                <option value="" selected="" disabled="">Select SubCategory
                                </option>

                            </select>
                            @error('subcategory_id')
                                <span ><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>

                        <div >
                            <label for="formLayoutAddress1">SubSubCategory</label>
                            <select name="subsubcategory_id"  id="test">
                                <option value="" selected="" disabled="">Select SubSubCategory
                                </option>
                            </select>
                            @error('subsubcategory_id')
                                <span ><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        </form>

CodePudding user response:

Based on your explanation, I think you're looking for this:

$(document).on('change', '[data-child]', function() {
  const selected_group = $(this).val();
  let el = $(`#${$(this).attr("id")}`);
  if (selected_group === null) {
    el.hide();
  } else {
    el.show();
  }
  let child_select = $("#"   $(this).attr("data-child"));
  value = child_select.find("option").hide().filter(function(i, e) {
      return $(e).val().startsWith(selected_group);
    }).show().eq(0).val();
  child_select.val(value);
  child_select.trigger("change");
});
$("[data-child]").eq(0).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div >
  <div >
    <span>Operating system</span>
    <select data-child="niv1" >
      <option value="1-1">Android</option>
      <option value="1-2">Linux</option>
      <option value="1-3" selected>Windows</option>
    </select>
  </div>
  <div >
    <span>System version</span>
    <select id="niv1" data-child="niv2" >
      <option data-group="1-1" value="1-1-1">9.0 Pie</option>

      <option data-group="1-2" value="1-2-1">Ubuntu</option>

      <option data-group="1-3" value="1-3-1">Windows 7</option>
      <option data-group="1-3" value="1-3-2">Windows 8</option>
      <option data-group="1-3" value="1-3-3">Windows 10</option>
    </select>
  </div>
  <div >
    <span>Edition</span>
    <select id="niv2" data-child="niv3" >
      <option data-group="1-2-1" value="1-2-1-1">Trusty Tahr</option>
      <option data-group="1-2-1" value="1-2-1-2">Xenial Xerus</option>
      <option data-group="1-2-1" value="1-2-1-3">Bionic Beaver</option>

      <option data-group="1-3-1" value="1-3-1-1">Windows 7 Home</option>
      <option data-group="1-3-1" value="1-3-1-2">Windows 7 Pro</option>

      <option data-group="1-3-2" value="1-3-2-1">Windows 8 Home</option>
      <option data-group="1-3-2" value="1-3-2-2">Windows 8 Pro</option>

      <option data-group="1-3-3" value="1-3-3-1">Windows 10 Home</option>
      <option data-group="1-3-3" value="1-3-3-2">Windows 10 Pro</option>
    </select>
  </div>
  <div >
    <span>Build</span>
    <select id="niv3" data-child="niv4" >
      <option data-group="1-2-1-2" value="1-2-1-2-1">18.04 LTS</option>

      <option data-group="1-3-1-1" value="1-3-1-1-1">Win 7 Home - A</option>
      <option data-group="1-3-1-1" value="1-3-1-1-2">Win 7 Home - B</option>

      <option data-group="1-3-1-2" value="1-3-1-2-1">Win 7 Pro - A</option>
      <option data-group="1-3-1-2" value="1-3-1-2-2">Win 7 Pro - B</option>

      <option data-group="1-3-2-1" value="1-3-2-1-1">Win 8 Home - A</option>
      <option data-group="1-3-2-1" value="1-3-2-1-2">Win 8 Home - B</option>

      <option data-group="1-3-2-2" value="1-3-2-2-1">Win 8 Pro - A</option>
      <option data-group="1-3-2-2" value="1-3-2-2-2">Win 8 Pro - B</option>

      <option data-group="1-3-3-1" value="1-3-3-1-1">Win 10 Home - A</option>
      <option data-group="1-3-3-1" value="1-3-3-1-2">Win 1 Home - B</option>

      <option data-group="1-3-3-2" value="1-3-3-2-1">Win 10 Pro - A</option>
      <option data-group="1-3-3-2" value="1-3-3-2-2">Win 10 Pro - B</option>
    </select>
  </div>
</div>

CodePudding user response:

So this is the way to make it work. If there is only one option You should probably trigger it manually after putting stuff in it so it runs with the first chosen option

The change is only called when the user changes it, and not after the AJAX runs. So in your case, you probably always want to call change to make sure your UI is in sync with what came from the server initially

  $('select[name="subcategory_id"]').on('change', function() {
                var subcategory_id = $(this).val();
            
                if (subcategory_id) {
                    $.ajax({
                        url: "{{ url('/category/subcategory/subsubcategory/product') }}/"  
                            subcategory_id,
                        type: "GET",
                        dataType: "json",
                      
                        success: function(data) {
                            var d = $('select[name="subsubcategory_id"]').empty();
                            $.each(data, function(key, value) {
                                $('select[name="subsubcategory_id"]').append(
                                    '<option value="'   value.id   '">'   value
                                    .subsubcategory_name   '</option>');
                            });
                            // the tigger is set here for one option in the select !!!
                            $("#test").trigger("change");
                        },

                    });
                } else {
                    alert('danger');
                }
            });
Then if there are multiple options the user will trigger them after so the first (initial) code would work.

  • Related