Search code examples
jqueryparameterssearch-engine

Use jquery to insert search parameters in URL


I have some different search parameters, which can be dynamical in different categories. My problem is, that I need to use jquery to check if there is clicked on a check box and then change the URL so that the parameters are inserted.

My HTML for one search parameter box is:

<h3>{heading}</h3>
<div class="{class} {parameter} searchParam" name="class">
    <ul>
        <li><input type="checkbox" name="{name}" value="{value}" />{value}</li>
    </ul>
</div>

Every parameter has "searchParam" as class - the other to parameters are dynamical.

What I need to is for every .searchParam to be created a URL part so that if e.g. 3 search params had checked values (the input in the li), then the URL would be like this:

http://domain.com/param1=value1,value2,value3.param2=value1,value2.param2=value1

Is this possible?


Solution

  • I solved it this way:

    $(document).ready( function() {
            var params = [];
    
            $(".searchParam").click(function(){
                params = [];
                $(".searchParam").each(function(index){
                    var name = $(this).attr('name');
                    var values = $('.'+ name +' input:checkbox:checked').map(function (){ return this.value }).get();
    
                    if(values.length > 0){
                        params.push({'name': name, 'values': values }); 
                    }           
                });
    
                var curUrl = $(location).attr('href');
                var newUrl = curUrl.split('/');
                var urlNumPar = newUrl.length - 1;
    
                var redirectURL = '';
    
                $(newUrl).each(function(index, val){
                    if( index == urlNumPar)
                    {
                    } else {
                        redirectURL += val+"/";
                    }
                });
    
                $(params).each(function(index, val){
                    if(params.length > 1 && index > 0)
                    {
                        redirectURL += ".";
                    }
                    redirectURL += val['name'] + "=" + val['values'];
                });
    
                window.location.href = redirectURL;
            });
        });