auto checkbox based from url value using javascript/jQuery

前端 未结 2 799
走了就别回头了
走了就别回头了 2021-01-22 11:52

Is there way to or it is possible to do it using javascript/jQuery?

Based Link URL: first one will check Type A and Type B and second example will check Type D



        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 12:13

    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.

提交回复
热议问题