Search code examples
javascripturlget

Adding to a url to tick a checkbox


I have a URL www.example.com/index.html

It has an element with an id of DARK_MODE. It is a checkbox.

I want to add to the URL so that when it loads it automatically gets ticked.

I tried www.example.com/index.html?DARK_MODE=checked

This is not my website that i'm loading.

Am i doing this right?

Thanks.


Solution

  • Here is the solution that I propose. In order to check the checkbox, use, ?DARK_MODE=checked.

    var $_GET = {};
    if(document.location.toString().indexOf('?') !== -1) {
        var query = document.location
            .toString()
            .replace(/^.*?\?/, '')
            .replace(/#.*$/, '')
            .split('&');
        for(var i=0, l=query.length; i<l; i++) {
            var aux = decodeURIComponent(query[i]).split('=');
            $_GET[aux[0]] = aux[1];
        }
    }
    
    if($_GET['DARK_MODE'] === 'checked') document.getElementById('DARK_MODE').checked = true;
    <input type="checkbox" id="DARK_MODE" />