[Answered ]-Django htmx change hx-get url after user input from radio buttons

1👍

Basically you are changing a single attribute (hx_get) based on a click. HTMX would make this a roundtrip to the server which seems inefficient as all the data is there on the page (assuming the value of the radiobuttons is the slug you are after). You can do this with pure javascript which would make the process much faster

<script>
    //get the form
    const venueForm = document.getElementById('venue-options')
    //when implementing, replace [name='radio'] with name of radio input fields
    const venueRadioButtons = document.querySelectorAll("input[name='radio']")
    //get the default venue URL for later alteration
    const venueURL = venueForm.getAttribute('hx_get')
    
    // create a clickhandler to change the URL to selected radiobutton
    const clickHandler = () => {
      //get the slug value
      let radioButtonSlug=document.querySelector("input[name='radio']:checked").value
      //use reguylar expression to replace last '/word/' value with slug value
      let newVenueUrl = venueURL.replace(/\/\w+\/$/, "/" + radioButtonSlug + "/")
      //reset the the hx_get value
      venueForm.setAttribute('hx_get', newVenueUrl)
    };
    
    // Assign the handler to the radiobuttons
    venueRadioButtons.forEach(i => i.onchange = () => clickHandler());
</script>

Leave a comment