skip to Main Content

So basically, I have this code taken from Advanced Custom fields Ressource center:

<script type="text/javascript">
(function($) {
    
    // change
    $('#archive-filters').on('change', 'input[type="checkbox"]', function(){

        // vars
        var url = '<?php echo '//' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>';
            args = {};
            
        
        // loop over filters
        $('#archive-filters .filter').each(function(){
            
            // vars
            var filter = $(this).data('filter'),
                vals = [];
            
            
            
            
            // find checked inputs
            $(this).find('input:checked').each(function(){
    
                vals.push( $(this).val() );
            });
            
            
            // append to args
            args[ filter ] = vals.join(',');
            
        });
        
        
        // update url
        if (url.indexOf('?') > -1){
            //code
        url += '&';
        }
        else {  
        url += '?';
        }
        
        
        // loop over args
        $.each(args, function( name, value ){
            if (value==='') {
                url += '';
            }else {
                url += name + '=' + value + '&';
            }
            
        });
        
        
        // remove last &
        url = url.slice(0, -1);
        
        // reload page
        window.location.replace( url );
        

    });

})(jQuery);
</script>

When I check a checkbox in #archive-filters div, it reloads the page with the new parameter in url.

Now I Would like to remove the parameter when the checkbox is unchecked but can’t find How.

How can I remove the url parameter associated to the checkbox unchecked?

2

Answers


  1. The easiest way to handle all of this is with the URL API and URLSearchParams

    I’m not 100% clear what the search params look like for that WP plugin so have used some very simple ones and am only using their keys to match checkbox names .

    Also not sure if the active ones are checked or not on page load but show how to do it here if they are not

    Since the URL object can be updated as many times as you need it may also offer you an alternative to reloading every time checkbox is checked and allow users to make multiple selections before reloading

    const url = 'http://example.com?foo=true&bar=true' // demo version
    // const url = location.href - live version
    const urlObj = new URL(url);
    const params = urlObj.searchParams
    
    const $checks = $(':checkbox')
    
    // on page load check the ones that exist un url
    params.forEach((val, key) => $checks.filter('[name="' + key + '"]').prop('checked', true));        
    
    $checks.change(function(){
        // append when checkbox gets checked and delete when unchecked
        if(this.checked){
            params.append(this.name, 'true')
        }else{
            params.delete(this.name);       
        }
        // do your page load with location.href = urlObj.href
         console.clear()
         console.log(urlObj.href);
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label>Foo <input type="checkbox" name="foo"/></label> 
    <label>Bar <input type="checkbox" name="bar"/></label>
    <label>Zzz <input type="checkbox" name="zzz"/></label>
    Login or Signup to reply.
  2. Very good code, I used it to add or remove a DEBUG flag in the URL.

    To have the URL like:

    http://www.example.com/?foo=1&bar=2&debug=1
    

    Here is my modified version:

    <label>
        <input type="checkbox" id="debug" value="1" <?= ($_GET['debug'] == '1' ? 'checked' : '') ?> />
        Debug
    </label>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <script>
    $('#debug').click(function(e)
    {
        const url_obj = new URL(location.href);
        const params = url_obj.searchParams;
    
        // Append when checkbox gets checked and delete when unchecked
        if (this.checked) {
            params.append(this.id, '1');
        } else {
            params.delete(this.id);
        }
    
        window.location = url_obj.href;
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search