Home > Software engineering >  add selected attribute to option if condition true
add selected attribute to option if condition true

Time:07-10

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 >
   <button  onclick="editSubCategory({{ $subcategory }})">Edit</button>
</div>
<!-- Edit Modal -->
<div  id="editSubCategoryModal" tabindex="-1" aria-labelledby="editSubModalLabel"
   aria-hidden="true">
   <div >
      <div >
         <div >
            <h5  id="editSubModalLabel">Edit Sub Category</h5>
            <button type="button"  data-bs-dismiss="modal" aria-label="Close"
               id="close-modal"></button>
         </div>
         <form id="EditForm">
            @csrf
            <div >
               <input type="hidden" name="subcategoryid_efield" id="subcategoryid_efield">
               <div >
                  <label for="categoryid_efield" >Category Name</label>
                  <select  aria-label="Default select example" id="categoryid_efield">
                  </select>
               </div>
               <div >
                  <label for="subcategoryname_efield" >Sub Category Name</label>
                  <input type="text" name="subcategoryname_efield" id="subcategoryname_efield"  placeholder="Enter Sub Category Name" />
               </div>
            </div>
            <div >
               <div >
                  <button type="button"  data-bs-dismiss="modal">Close</button>
                  <button type="submit"  id="edit-btn">Update</button>
               </div>
            </div>
         </form>
      </div>
   </div>
</div>
<!-- End Edit Modal -->

CodePudding user response:

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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div >
  <button id="buttonedit"  onclick="editSubCategory()">
  <div ><span  role="status" aria-hidden="true"></span></div>
  edit
</button>
</div>


<!-- Modal -->
<div  id="editSubCategoryModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div >
    <div >
      <div >
        <h5  id="exampleModalLabel">Modal title</h5>
        <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div >
        <select id="categoryid_efield"  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 >
        <button type="button"  data-bs-dismiss="modal">Close</button>
        <button type="button" >Save changes</button>
      </div>
    </div>
  </div>
</div>

  • Related