Paulo Dos Santos Paulo Dos Santos - 1 month ago 8
HTML Question

Custom URL from a checkbox form

I am trying to create a custom url from some checkboxes.

<form method="get" action="/search">
<input type="checkbox" name="q" value="label:TAG1" />TAG1<br />
<input type="checkbox" name="q" value="label:TAG2" />TAG2<br />
<input type="checkbox" name="q" value="label:TAG3" />TAG3<br />
<input type="submit" value="Filtrar" />
</form>


I have this: http://www.exemple.com/search?q=label:TAG1&q=label:TAG2&q=label:TAG3

But I want this: http://www.exemple.com/search/?q=label:TAG1|label:TAG2|label:TAG3

Answer

Try with this:
(explanations are within the code)

$(document).ready(function(){
    $("form").on("submit",function(e){
        // Disable the button's submit.
        e.preventDefault();

        // Start setting a custon query.
        var query="?q=";

        // Check each checked checkboxes.
        $("input[type='checkbox']:checked").each(function(index){
            // Adds | only on second and next...
            if(index>0){
                query+="|";
            }
            // Adds the value.
            query+=$(this).val();
        });
        //Redirect with the query in GET
        console.log( $(this).attr("action")+query );
        window.location=$(this).attr("action")+query;
    });
});

CodePen

EDIT

Add this to your <head>:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Comments