简体   繁体   中英

Jquery to Vanilla Javascript get attribute data

I'm sorry, i want to ask, i want to change Jquery to Vanilla JS, but i don't understand about jquery and javascript logic

<a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?= $row->product_id;?>" data-name="<?= $row->product_name;?>">Edit</a>

$(document).ready(function(){

    // get Edit Product
    $('.btn-edit').on('click',function(){
        // get data from button edit
        const id = $(this).data('id');
        const name = $(this).data('name');
        // Set data to Form Edit
        $('.product_id').val(id);
        $('.product_name').val(name);
        // Call Modal Edit
        $('#editModal').modal('show');
    });

});

if possible to change jquery to vanilla/ plain javascript or can you tell me reference about this case if you know? thanks ps: I'm sorry if wrong, i just joined stack overflow today and my English skills are bad

Use document.querySelector() to get the desired elements and Element.getAttribute() to get the custom data attributes:

$(document).ready(function() {
  const btnEdit = document.querySelector(".btn-edit");
  const prodId = document.querySelector(".product_id");
  const prodName = document.querySelector(".product_name")
  const modal = document.querySelector("#editModal");

  btnEdit.addEventListener("click", (evt) => {
    const id = evt.target.getAttribute('data-id');
    const name = evt.target.getAttribute('data-name')
    prodId.value = id;
    prodName.value = name;
    modal.classList.add("show") //--> some css class to display the modal
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM