URL encoding fix for calculator links

#1

I noticed that when creating a shareable calculator link, it wasn’t properly escaping the memo field. While technically it was still a valid URI, when pasting into email clients and such the auto link parsing would fail and could cut off the link.

I looked at the code and simplified the encoding and creation of the shareable link, fixing the issue.

The following is a drop-in replacement for the writeQuery function on line 1212 of the calculator page:

function writeQuery() {
    var params = [
        ['make', $("#make_dropdown option:selected").val()],
        ['miles', $("#miles option:selected").val()],
        ['msd', $("#msd option:selected").val()],
    ], calc_url;

    inputArr.forEach(function(name) {
        params.push([name, $("#" + name).val()]);
    });
    checkArr.forEach(function(name) {
        if ($("#" + name).is(":checked")) {
            params.push([name, 'true']);
        }
    });

    calc_url = written_url + params.map(function(param) {
        // No keys are currently unsafe, but might as well encode both
        return encodeURIComponent(param[0]) + '=' + encodeURIComponent(param[1])
    }).join('&');

    console.log(calc_url); // Previous version logged to console

    $("#display_url").val(calc_url).select();
    document.execCommand("copy");
}

This properly encodes both the keys and values before adding to query string.

Then on the parsing side, you just have to update lines 1171, 1172 of the parseQuery function to properly decode:

var queryKey = decodeURIComponent(splitArray[0]);
var queryValue = decodeURIComponent(splitArray[1]);

And in line 1178 you can then do away with all the manual regex find/replace and set value with:

$("#" + inputArr[n]).val(queryValue);

That’s my way of saying thanks for a helpful site… hopefully saving you a few minutes of bug fixing time.

3 Likes
#2

Thank you. This should be helpful for @littleviolette.

#3

@chris4beta This works wonderfully. Thank you for your help! Rolling it out in the next calculator update.

We are now on the testing stage before we roll out the next calculator update. We invite all those who would be interested in helping out! PM me or @michael for the testing link. :slight_smile: