开发者

Grab URL parameters to maintain search form options using jQuery or javascript

I have a set of search filters that set a URL string (for further processing). As the page reloads to show the results, the options selected by the user are lost. I was wondering if it's possible to use jquery to capture the parameters from the url and 'remember' what options had been selected?

For example, if my URL contained www.something.com/index.html?&colour=red&circle=1&star=0, my form would load with the following:

<h3>Colour</h3&开发者_运维问答gt;
<p>Blue: <input name="colour" type="radio" value="blue" /></p>
<p>Red: <input name="colour" type="radio" value="red" /></p> [selected]
<p>Green: <input name="colour" type="radio" value="green" /></p>

<h3>Shape</h3>
<p>Circle: <input name="circle" type="checkbox" value="1" /></p> [selected]
<p>Square: <input name="square" type="checkbox" value="1" /></p>
<p>Star: <input name="star" type="checkbox" value="1" /></p>

Thanks for looking.


You can use the following JS object

location.search

This will give you the Query String Params of your address bar


<script type="text/javascript">
function getQueryStr(name) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
}}}

$(document).ready(function() {
    $('input[name=color]').val(getQueryStr("colour"));
    $('input[name=circle]').prop("checked", (getQueryStr("circle")=="1"));
    $('input[name=square]').prop("checked", (getQueryStr("square")=="1"));
    $('input[name=star]').prop("checked", (getQueryStr("star")=="1"));
});
</script>


This information is held on the location object Location in javascript from where you will have to extract the parameters.


You could get url parameter using this function (look here Append urlVariable to next page's link):

function getParameterByName( name )

    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

var colour= getParameterByName('colour');
var circle= getParameterByName('circle');
var star= getParameterByName('star');

When you have the parameters then it's easy to select them:

$('input[name=colour][value='+colour+']').attr('checked', 'checked');


Unless there is a particular reason you need to do this on the client side:

This usually is done on the server side. You can check for parameters on the server side (which you probably do anyway) and send the HTML markup with preselected checkboxes back to the client.

On the plus side, this will also work with javascript disabled browsers as well as search engines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜