简体   繁体   中英

Jquery to modify URL based on an IF?

I have a URL that does a filter and spits out some products the structure looks like below:

/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=185,223

Now on this there is a sort function and if I was to use this with out filtering as above the URL would look like the below:

/Products/Catalogue.aspx?orderby=price&desc=1&psize=9

If I currently try and filter and then sort, the sort overwrites myfilter, so the filter becomes null and void.

So what I need it do is be aware that IF i have a filter then append the sorting after 'catfilter=' part in the URL so the URL would then look like

/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=8,188&orderby=man&desc=0&psize=36

The gotcha is that there is not always going to be a filter added in which case the URL would be:
/Products/Catalogue.aspx

<select id="listSort" class="NormalTextBox SortCatalogue" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listLength')[getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
    <option value="?orderby=name&amp;desc=0&amp;">Sort by</option>
    <option value="?orderby=price&amp;desc=0">Lowest price</option>
    <option value="?orderby=price&amp;desc=1">Highest price</option>
    <option value="?orderby=man&amp;desc=0">Brand A-Z</option>
    <option value="?orderby=man&amp;desc=1">Brand Z-A</option>
    <option value="?orderby=name&amp;desc=0">Title A-Z</option>
    <option value="?orderby=name&amp;desc=1">Title Z-A</option>
    <option value="?orderby=ref&amp;desc=0">Code asc</option>
    <option value="?orderby=ref&amp;desc=1">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listSort')[getElementById('listSort').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
    <option value="?psize=9&foo">Page size</option>
    <option value="?psize=6">6 per page</option>
    <option value="?psize=9">9 per page</option>
    <option value="?psize=18">18 per page</option>
    <option value="?psize=36">36 per page</option>
</select>

<script type="text/javascript">

    var searchString = window.location.search.substring(1);
    var i, val;
    var params = searchString.replace('?','&').split('&');
    var pgsize,pgorder,pdesc,searchstr; 
    pgsize = 9;
    pgorder = 'name';
    pdesc = 0;
    searchstr='';
    for (i=0;i<params.length;i++) {
        val = params[i].split('=');
        if(val[0]== "psize")
            pgsize=val[1];
        else if(val[0]== "orderby")
            pgorder=val[1];
        else if(val[0]== "desc")
            pdesc=val[1];
        else if((val[0]).toLowerCase()== "search") { 
            searchstr=val[1]; 
        }
    }
    document.getElementById('listLength').value='?psize=' + pgsize;
    document.getElementById('listSort').value ='?orderby=' + pgorder + '&desc=' + pdesc;

    if(searchstr!='') {
        searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
        document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
        document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
        document.getElementById('searchtxthdrright').innerHTML= '"' ;
        document.getElementById('searchtxt').innerHTML = searchstr;
    }
 </script>

Ok lets take a step back from the problem. I think you need to add a bit more structure instead of haphazardly adding and removing bits of url code here and there :)

You have tagged the post as jQuery so i'm going to use that although you haven't actually used it in your posted code.

The whole idea is going to be around creating a JavaScript object and using it as a lightweight dictionary , and the jQuery .param() function which will encode it for us at the end.

Lets change the markup to this:

<select id="listSort" class="NormalTextBox SortCatalogue">
    <option value="nameDesc">Sort by</option>
    <option value="priceAsc">Lowest price</option>
    <option value="priceDesc">Highest price</option>
    <option value="manAsc">Brand A-Z</option>
    <option value="manDesc">Brand Z-A</option>
    <option value="nameAsc">Title A-Z</option>
    <option value="nameDesc">Title Z-A</option>
    <option value="refAsc">Code asc</option>
    <option value="refDesc">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength">
    <option value="9">Page size</option>
    <option value="6">6 per page</option>
    <option value="9">9 per page</option>
    <option value="18">18 per page</option>
    <option value="36">36 per page</option>
</select>
<input type="text" id="searchstr">
<button id="searchbutton">Search!</button>

As you will see I've also thrown in a textbox and a button as you refer to searchstr in your code.

Instead of encoding and extracting we are just going to store some parseable values in the select options. We're also going to use an unobtrusive javascript technique by using the ID to attach an onchange handler rather than injecting the javascript into the markup (this will be added later on).

Now we need to write some JavaScript code that can build us a querystring. Instead of directly building a querystring though we will be making a javascript object. Then later on that will be used to generate the query string.

I've written a search function that just displays the query string we generated rather than redirect the user.

I've also added in some event handlers so this is triggered as your code was triggering.

function getFiltersAsQueryString() {
    var $listSort = $("#listSort"),
        $listLength = $("#listLength"),
        $searchQuery = $("#searchstr");
        queryStringDict = {};

    // extract page size
    queryStringDict["psize"] = $listLength.find("option:selected").val();    

    // extract sort order and direction
    var selectedItem = $listSort.find("option:selected").val();    
    queryStringDict["orderby"] = /^[a-z]*/.exec(selectedItem)[0];
    queryStringDict["desc"] = /Desc$/.exec(selectedItem) == "Desc" ? 1 : 0;

    // extract search
    queryStringDict["search"] = $searchQuery.val();

    return $.param(queryStringDict);
}

function searchWithFilters() {
    // normally you would do a window.location here to redirect
    alert(getFiltersAsQueryString());
}

$(document).ready(function () {
    // wire up our handlers
    $("#listSort").change(searchWithFilters);
    $("#listLength").change(searchWithFilters);
    $("#searchbutton").click(searchWithFilters);
});

And then at the end of the day when you put all this together you get this:

I don't think this is quite a complete solution yet.

  1. Need to add in the cat filter
  2. Probably want to preselect the controls based on the query string?

I just wanted to post this to see if its going in the right direction.

Hugly helpful thank you, ended up going with this some JS and Jquery in up to come up with the complete solution:

<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr,catfilter;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if(val[0]== "catfilter")
catfilter=val[1];
else if((val[0]).toLowerCase()== "search")
{ searchstr=val[1]; }
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' pgorder '&desc=' + pdesc;
if(searchstr!='')
{
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}

if(catfilter)
{
document.getElementById('searchstrdiv').innerHTML=                 document.getElementById('searchstrdiv').innerHTML + '&catfilter=' + catfilter ;
}

</script>

<script type="text/javascript"> 
$(document).ready(function(){

$('.SortCatalogue').removeAttr('onchange');
$('.SortCatalogue').change(function() {newURL();});
$('.PageLength').removeAttr('onchange');
$('.PageLength').change(function() {newURL();});

function newURL()
{

var newParams = document.getElementById('listSort')    [document.getElementById('listSort').selectedIndex].value + '&amp;' +     document.getElementById('listLength')    [document.getElementById('listLength').selectedIndex].value.split('?')[1] +     document.getElementById('searchstrdiv').innerHTML.replace('amp;','');

var oldPathname = location.pathname;
oldPathname = oldPathname.replace('/desc/','/').replace('/orderby/', '/');

document.location.href = oldPathname + newParams;

}

});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM