I may make the same mistake again because I don't understand much now. Keep a record so that you can look back and check it at that time.
While implementing the delete function with rails, I want to display a confirmation dialog before deleting, so I write it in the Javascript file.
html.erb
<%= link_to 'Delete', hoge_path(hoge.id), class: 'delete-btn', method: :delete %>
javascript
function check() {
const btn = document.getElementsByClassName('delete-btn');
btn.addEventListener('click', () => {
window.confirm('Perform a delete')
})
};
I try to click the delete button, but the dialog does not appear and the deletion is executed. It reloads and tries again, but it is deleted without anything.
Changed the description of the html file as follows
html.erb
<%= link_to 'Delete', hoge_path(hoge.id), class: 'delete-btn', method: :delete, data: { confirm: 'Deleteを実行します。よろしければOKをクリックしてください。' } %>
After checking, it is said that a dialog will be displayed if you write ``` data: {confirm:" words to be displayed "}` in
link_to``. Solved for displaying dialog.
So what if you want to use addEventListener
in a JavaScript file?
`querySelectorAll``` → Use the
forEach`` function for the obtained elementThe foreach
function is a method of the NodeList object, and NodeList is the return value of querySelectorAll
. Therefore, use querySelectorAll
instead of `` getElementsByClassName``` to get the elements. <br> By the way, the return value of ``` getElementsByClassName``` is
`HTMLCollection```.
I'm still not very familiar with it, and since I'm writing by connecting what I've researched for the time being, there are many parts that I can't understand. I felt that I had to study so that I could deepen my understanding.
Recommended Posts