单击复选框更新查询字符串

时间:2015-07-24 11:25:47

标签: javascript jquery

有n个输入框,如果用户选中了任何复选框,则查询字符串中的值应加上复选框名称,如果用户取消选中该复选框,则应省略该值。如果复选框名称相同,值应该加上逗号分隔 防爆。 ?NAME1 = 1,2,3&安培;名称2 = 9,8,10

1 个答案:

答案 0 :(得分:0)

$("template_filters").on("change", "input", function(event, element) {
    var path        =   window.location.search.substring(1);
    var attr_name   =   element.name;
    var attr_val    =   element.readAttribute('data-id');
    var currentqueryVar =   path.toQueryParams();
    var org_path    =   window.location.href;
    var cleanUrl    =   org_path.split('?');
    if(path.length > 0 && typeof currentqueryVar[attr_name] !== 'undefined')
    {   
        var paramArray = path.split("&");
        var n = new Array();
        var i;
        for (i=0;i<paramArray.length;i++)
        {
           var  currentParameter = paramArray[i].split("=");
           if(currentParameter[0]==attr_name)//Parameter already exists in current url
           {
                var old_q_val   =   currentParameter[1].split(',');
                if(old_q_val.indexOf(attr_val)=== -1)
                    old_q_val.push(attr_val);
                else
                {
                    var unset_index = old_q_val.indexOf(attr_val);
                    if(unset_index != -1){
                         old_q_val.splice(unset_index, 1);
                    } 
                }
                currentParameter[1] =old_q_val.join();
           }
           if(currentParameter[1]!='')
                n.push(currentParameter[0]+'='+currentParameter[1]);
        }
        var queryStrnig ='?'+ n.join("&");
    }
    else{
        queryStrnig ='?'+attr_name+'='+ attr_val;
        if(path!='')
            queryStrnig ='?'+path+'&'+attr_name+'='+ attr_val; 
    }
    history.pushState(null, null, cleanUrl[0]+queryStrnig);
    return false;
});