I'm making a website with HTMX. I usually manage to do what I want with HTMX but I have a problem activating an hx-post with a dynamic URL. I have a list of items that the user must be able to rename and for that I open a modal. When I press the save button of my modal it must activate an hx-post that will send the new name to my API. I need a dynamic URL to have only once the HTML code of my modal without having to hardcode it for each item in the list
Here is the HTML code that I currently have:
<div id="renameModal" class="fixed hidden">
<div>
<h2 >Rename Document</h2>
<form id="renameForm" hx-swap="outerHTML">
<input type="hidden" id="docIdInput" name="docId" value="">
<div>
<label for="nameInput" >New Name</label>
<input type="text" id="nameInput" name="name" class="required">
</div>
<div>
<button type="button" id="cancelButton" >Cancel</button>
<button type="submit" >Save</button>
</div>
</form>
</div>
</div>
<script>
function openRenameModal(docId, docTitle) {
document.getElementById('renameModal').classList.remove('hidden');
document.getElementById('docIdInput').value = docId;
// #title-docId is the id of the p-tag that need to be replace by the api response
document.getElementById('renameForm').setAttribute('hx-target', '#title-' + docId);
document.getElementById('renameForm').setAttribute('hx-post', '/document/rename/' + docId);
document.getElementById('nameInput').value = docTitle;
}
document.getElementById('cancelButton').addEventListener('click', function() {
document.getElementById('renameModal').classList.add('hidden');
});
document.getElementById('renameForm').addEventListener('htmx:afterSwap', function(event) {
if (event.detail.xhr.status === 200) {
document.getElementById('renameModal').classList.add('hidden');
}
});
</script>
When I press "Save" my modal disappears and I am redirected to <url of my site>/<an ID>?docId=<id of the doc a want to rename>&name=<the new name>
while I do not want to be redirected, I just want to make a post request to my api and have the document renamed for the client by what the api returns.
How can I make my site work the way I want it to?
The problem is that htmx has to parse the tags before the js can set the attributes dynamically
I solved this problem by making a GET route that returns the modal like that no need to use javascript or make dynamic attributes. It's simpler and easier to code