在多个复选框组单击中在url中附加参数

时间:2017-07-08 11:51:14

标签: javascript jquery url post

我想在复选框点击时重写url参数值,类似于LinkedIn Advance搜索。



<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
  <script type='text/javascript'>
  
  $(document).ready(function () {
$('input[type=checkbox]').click(function (e) {
var seasoning = jQuery.map($(':checkbox[id=seasoning\\[\\]]:checked'), function (n, i) {return n.value;}).join(',');

window.location ='example.com?seasoning='+seasoning;
 
});

});
</script>
&#13;
<h3>Filter recepies:</h3>

<div>
<p>Select vegetables</p>
<label><input type="checkbox" id="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" id="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" id="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" id="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" id="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" id="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div>
&#13;
&#13;
&#13;

我想要的结果

Click1:当我从菜单中点击Potato时,我的网址应如下所示
example.com?vegitables=potato

Click2:当我从菜单中点击Onion时,我的网址应如下所示
example.com?vegitables=potato,onion

Click3:当我从调料中点击盐时,我的网址应如下所示
example.com?vegitables=potato,onion&seasoning=salt

Click4:当我点击辣椒调味时,我的网址应如下所示
example.com?vegitables=potato,onion&seasoning=salt,pepper

1 个答案:

答案 0 :(得分:0)

这是你可以做的事情

$(document).ready(function () {
  $('input[type=checkbox]').click(function (e) {
  var seasoning = '', tempArray = [];
  $('input[name="vegetables[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='vegetables='+tempArray.toString();
     tempArray = [];
  }
  
  $('input[name="seasoning[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='&seasoning='+tempArray.toString();
  }
 
 // window.location ='example.com?seasoning='+seasoning;
 console.log('example.com?'+seasoning);

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" name="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" name="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" name="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" name="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" name="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" name="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div>

为简单起见,进一步编辑此处是指向工作JSFIDDLE

的链接