remove the ? and name= in get method html

Issue

I made a quick code in html and js. The thing i want to do is via method get, to send the <select> into the url but without the ? symbol, and also the names in the select attributes. For example if I click the button, the url will appear

https://mytesting.com/?marca=HEREGOESTHESELECTEDITEM&modelo=HEREGOESTHESELECTEDITEM&ano=HEREGOESTHESELECTEDITEM`

What i want to do, is just to remove the ? and the names marca= &modelo= and &ano= and only show the selected items. For example:

`https://mytesting.com/Firstelement-Secondelement-Thirdelement

This is my html code

 <form name="marcas" action="https://mytesting.com">

                <select name="marca" onchange="relation()">
          <option value="-">Marca</option>
          <option value="vw">VW</option>
          <option value="nissan">Nissan</option>
          <option value="audi">Audi</option>
          <option value="bmw">BMW</option>
          <option value="buick">Buick</option>
          <option value="chevrolet">Chevrolet</option>
        </select>

                <select name="modelo">
          <option value="modelo">Modelo</option>"
        </select>

                <select name="ano">
          <option value="ano">Año</option>
        </select>
                <button class="button1" id="send" type="submit" method="GET">Buscar</button>

            </form>

And the javascript I made, just shows the corresponding items that are in an array.

Solution

You’ll need to use JavaScript to intercept the submit event and craft the new URL

document.querySelector("form[name=marcas]").addEventListener("submit", (e) => {
  e.preventDefault(); // stop the normal form submit action

  const data = new FormData(e.target); // capture all the fields
  const url = new URL(e.target.action); // start with the form action

  // create the pathname by joining together all the field values
  url.pathname = Array.from(data, ([_, val]) => val).join("-");

  // now redirect to the new URL
  location.href = url;
});

Answered By – Phil

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.