1

I have a Laravel 9 project where i manage Add, Edit & Delete of Sub Categories using Bootstrap Modal. In Edit Modal list of Categories presented as dropdown menu options added by help of jQuery. When click on Edit button i have call editSubCategory function but I can not specify the selected option in dropdown menu base of saved value in database basically this should be when option.val() == selectedCategoryID when this true we should make this option selected so i have try this after adding options to editSubCategoryModal through jQuery by using the code below but it look like return something not understand it S.fn.init [prevObject: S.fn.init(1)] So i need help to understand how thing should work correctly and this is my current code:

function editSubCategory(e) {
  let subCategoryId = e.id;
  let subCategoryName = e.sub_category_name;
  let selectedCategoryID = e.category_id;

  $("#subcategoryid_efield").val(subCategoryId);
  $("#subcategoryname_efield").val(subCategoryName);

  let url = window.location.origin;
  let path = url + "/getcategories";
  axios
    .get(path)
    .then((res) => {
      $("#categoryid_efield").html(
        '<option value="" disabled>--Select Category--</option>'
      );
      $.each(res.data, function (key, value) {
        $("#categoryid_efield").append(
          '<option value="' +
            value.id +
            '">' +
            value.category_name +
            "</option>"
        );
      });
    })
    .catch((err) => console.log(err));

  $("#categoryid_efield option[value='" + selectedCategoryID + "']").attr(
    "selected",
    "selected"
  );

  $("#editSubCategoryModal").modal("show");
}
<div class="edit">
   <button class="btn btn-sm btn-success edit-item-btn" onclick="editSubCategory({{ $subcategory }})">Edit</button>
</div>
<!-- Edit Modal -->
<div class="modal fade" id="editSubCategoryModal" tabindex="-1" aria-labelledby="editSubModalLabel"
   aria-hidden="true">
   <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
         <div class="modal-header bg-light p-3">
            <h5 class="modal-title" id="editSubModalLabel">Edit Sub Category</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"
               id="close-modal"></button>
         </div>
         <form id="EditForm">
            @csrf
            <div class="modal-body">
               <input type="hidden" name="subcategoryid_efield" id="subcategoryid_efield">
               <div class="mb-3 form-group">
                  <label for="categoryid_efield" class="form-label">Category Name</label>
                  <select class="form-select mb-3" aria-label="Default select example" id="categoryid_efield">
                  </select>
               </div>
               <div class="mb-3 form-group">
                  <label for="subcategoryname_efield" class="form-label">Sub Category Name</label>
                  <input type="text" name="subcategoryname_efield" id="subcategoryname_efield" class="form-control" placeholder="Enter Sub Category Name" />
               </div>
            </div>
            <div class="modal-footer">
               <div class="hstack gap-2 justify-content-end">
                  <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-success" id="edit-btn">Update</button>
               </div>
            </div>
         </form>
      </div>
   </div>
</div>
<!-- End Edit Modal -->
Q8Xbox
  • 33
  • 7
  • u probably run that function before document ready. look at this https://stackoverflow.com/questions/34494873/why-is-my-jquery-selector-returning-a-n-fn-init0-and-what-is-it – Rumeee Jul 08 '22 at 03:15
  • which variable u console log? S.fn.init [prevObject: S.fn.init(1)] is jquery collection. https://stackoverflow.com/questions/50725803/i-get-w-fn-init-prevobject-w-fn-init1-when-i-console-log – Rumeee Jul 08 '22 at 03:20
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Rumeee Jul 08 '22 at 03:32

1 Answers1

0

so S.fn.init [prevObject: S.fn.init(1)] is jQuery collection . use get() instead get the array console.log($("#categoryid_efield option[value='" + selectedCategoryID + "']").get())

that's because u trying to access element that is not present because the element being created in ajax request which is async. or if it's still fail i believe none of the data get from laravel is match with value from selectedCategoryID

function editSubCategory(e = {
  id: 1,
  sub_category_name: 'name',
  category_id: 3
}) {
  let subCategoryId = e.id;
  let subCategoryName = e.sub_category_name;
  let selectedCategoryID = e.category_id;

  $("#subcategoryid_efield").val(subCategoryId);
  $("#subcategoryname_efield").val(subCategoryName);
  $("#buttonedit").text("loading...")
  $("#buttonedit spin").toggleClass("d-none")


  let url = window.location.origin;
  let path = url + '/getcategories';
  let res = {
    data: [{
        id: 1,
        category_name: "a"
      },
      {
        id: 2,
        category_name: "b"
      }, {
        id: 3,
        category_name: "c"
      }
    ]
  }
  //axios.get(path)
  //.then( res => {
  //because i don't know the url i cant simulate using ajax so i test using timeout instead
  setTimeout(() => {
    $('#categoryid_efield').html(`<option value="" disabled>--Select Category--</option>`);

    $.each(res.data, function(key, value) {
      $('#categoryid_efield').append('<option value="' + value.id + '">' + value.category_name + '</option>');
    });
    //move it directly inside your promise
    $("#categoryid_efield option[value='" + selectedCategoryID + "']").attr("selected", "selected");
    $('#editSubCategoryModal').modal('show');
    $("#buttonedit").text("edit")
    $("#buttonedit spin").toggleClass("d-none")
  }, 5000)
  //.catch( err => console.log(err));
  //this will fail because the option with value selectedCategoryID doesnt exist yet.
  // $("#categoryid_efield option[value='" + selectedCategoryID + "']").attr("selected","selected");

  //$('#editSubCategoryModal').modal('show');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="edit">
  <button id="buttonedit" class="btn btn-sm btn-success edit-item-btn" onclick="editSubCategory()">
  <div class="d-none"><span class="spinner-grow spinner-grow-sm " role="status" aria-hidden="true"></span></div>
  edit
</button>
</div>


<!-- Modal -->
<div class="modal fade" id="editSubCategoryModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <select id="categoryid_efield" class="form-select" aria-label="Default select example">
          <option selected>Open this select menu</option>
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
Rumeee
  • 168
  • 1
  • 10
  • It is look like the element not fully loaded when editSubCategoryModal opened this is why the query for adding selected attribute always return null but when just testing it using setTimeOut it works fine the get the selected option correctly but i can not figure out the exact code that can help here since try multiple option the refer links all of them return null or error. https://codeshare.io/mp7w1k – Q8Xbox Jul 08 '22 at 04:39
  • maybe the way adding pass the data to editSubCategoryModal and display the dropdown menu need adjustment a little to make it work perfectly...?! – Q8Xbox Jul 08 '22 at 04:43
  • ohh... i forgot your function is inside promise. i fix it – Rumeee Jul 08 '22 at 06:02
  • Instead of using setTimeOut. Can we display "loading" animation until the dropdown menu fully loaded than apply selected attribute ? – Q8Xbox Jul 08 '22 at 18:56
  • setTimeout is only for simulating axios. because i cant use axios here – Rumeee Jul 08 '22 at 19:29