Dic 04

Change Url’s parameters Values

Tag: Codice, javascriptfenix @ 12:59

Snippet javascript per cambiare/aggiungere parametri ad un URL.

Per il corretto funzionamento é richiesto il framework jQuery.

Ultimo aggiornamento: 4 Dicembre 2009

/**
* parameterName: name of parameter to add.
* value: value of parameter.
* inputID: URL or input id of an object's DOM document.
*/
function changeParameterValue(parameterName, value, inputID) {
    var input = document.getElementById(inputID);
    var href = true;
    var url = "";

    if (input == undefined) {
        url = inputID;
    } else {
        url = input.getAttribute("href");
        if (url == undefined) {
            href = false;
            url = input.getAttribute("action");
        }
    }

    var parameters = {};
    parameters[parameterName] = value;
    url = changeParametersUrl({url: url, parameters: parameters});

    if (input != undefined) {
        if (href) {
            input.setAttribute("href", url);
        } else {
            input.setAttribute("action", url);
        }
    }
    return url;
}

/**
* OPTIONS
*
* Required
* url {string|object}: The url to change.
* parameters {map {key:value}}: Map of key/value parameters to add.
*/
function changeParametersUrl(options) {
    options = options || {};
    var defaults = {};
    var config = jQuery.extend({}, defaults, options);

    var runtimeChangeParameter = function(url, parameterName, value) {
        var params = {};
        params[parameterName] = value;
        var paramSerialized = jQuery.param(params);
        var valueSerialized = paramSerialized.replace(parameterName + '=', '');
        value = valueSerialized;

        if (url.split("?").length < 2) {
                url += "?";
        }

        if (!url.match(parameterName)) {
                if(url.substr(-1,1) != "?") {
                        url += "&";
                }
                url += parameterName + "=" + value;
        } else {
            var parameterString = url.replace(/.*\?(.*)/, "$1");
            var parameterTokens = parameterString.split("&");
            var parameterList = new Array();

            for (i = 0; i < parameterTokens.length; i++) {
                var parameterNameTmp = parameterTokens[i].replace(/(.*)=.*/, "$1");
                var parameterValueTmp = parameterTokens[i].replace(/.*=(.*)/, "$1");
                parameterList[parameterNameTmp] = parameterValueTmp;
            }
            url = url.replace(parameterName + '=' + parameterList[parameterName], parameterName + "=" + value);
        }
    return url;
    }

    var result_url = options.url;
    var parameters = config.parameters;
    for (key in parameters) {
        result_url = runtimeChangeParameter(result_url, key, parameters[key]);
    }
    return result_url;
}

Leave a Reply



Hello !