javascriptcheckbox

After selecting second checkbox, not appending to url along with first checkbox name


    $(document).ready(function () {
      $('input[type=checkbox]').click(function (e) {
      var seasoning = '', tempArray = [];
      $('input[name="Brand[]"]:checked').each(function(){
          tempArray.push($(this).val());
      })
      if(tempArray.length !== 0){
         seasoning+='&Brand='+tempArray.toString();
         tempArray = [];
      }

      $('input[name="Origin[]"]:checked').each(function(){
          tempArray.push($(this).val());
      })
      if(tempArray.length !== 0){
         seasoning+='&Origin='+tempArray.toString();
      }


     window.location = "/example.com" + seasoning;

      });

    });

When I run above code, it appends brand name to url. when I select origin, the brand name disappears and origin name appends. I want brand name to still be there.


Solution

  • This does not happen in a clean test:

    HTML

    <script
                  src="https://code.jquery.com/jquery-3.7.1.min.js"
                  integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
                  crossorigin="anonymous"></script>
    <input type="checkbox" name="Brand[]" value="A">
    <input type="checkbox" name="Brand[]" value="B">
    <input type="checkbox" name="Brand[]" value="C">
    <input type="checkbox" name="Brand[]" value="D">
    <input type="checkbox" name="Origin[]" value="E">
    <input type="checkbox" name="Origin[]" value="F">
    <input type="checkbox" name="Origin[]" value="G">
    <input type="checkbox" name="Origin[]" value="H">
    

    JS

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

    Fiddle: https://jsfiddle.net/jzcdLg9x/

    It results in URLs containing both the brand and the origin, like

    "/example.com&Brand=B,C&Origin=G,H"
    

    Screenshot taken from the fiddle illustrating what I described above:

    Illustration

    So your issue must come from something else, some other Javascript code that you have that does some computing and redirecting to the wrong place, of a cached JS file.