auto checkbox based from url value using javascript/jQuery

强颜欢笑 提交于 2019-12-02 00:22:07

Do it like this:

var i = document.location.href.lastIndexOf('?');
var types = document.location.href.substr(i+1).replace(/type=/g,'').split('&');
$('input[name="type"]').prop('checked',function(){
     return $.inArray(this.value,types) !== -1;
});

Explanation:

Consider the url is 'http://sample.com?type=A&type=C'. Then:

  • i is the index of '?' sign in that url
  • .substr() will cut type=A&type=C part from the url. After the cut, we will have this string:

    "type=A&type=C"
    
  • .replace() removes "type=" parts from the above mentioned string:

    "A&C"   //after replace
    
  • .split() splits that string into array:

     ["A","C"]
    
  • $.inArray() checks whether value of current checkbox is in the ["A","C"] array. If it is, then checks( .prop('checked',true) ) the checkbox.

nexus-bytes

This question shows a solution to check the query string parameters using javascript. There is also a link at the top to a possible duplicate question that provides a solution using JQuery.

Once you determine the querty string parameters, you can use jQuery to check the box (as detailed in another question):

$('input[value="A"]').prop("checked", true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!