I am trying to get the ULR parameter, but my code does not run because at debugging it shows me an error which is: Cannot read property 'split' of undefined
and I am not sure what I am doing wrong.
For example: default.html?pid=405 I need to get in a JavaScript variable the 405 value. This is the code i am using:
<script type="text/javascript">
function getUrlParameters(parameter, staticURL, decode) {
var currLocation = (staticURL.length) ? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for (var i = 0; i < parArr.length; i++) {
parr = parArr[i].value.split("=");
if (parr[0] == parameter) {
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
} else {
returnBool = false;
}
}
if (!returnBool) return false;
}
</script>
<script type="text/javascript">
function runDepo()
{
var idParameter = getUrlParameters("pid", "", true);
}
Can somebody help me? Thanks in advance.
asked Apr 29, 2016 at 20:11
Lanshore
431 gold badge1 silver badge9 bronze badges
1 Answer 1
Just remove .value from parr = parArr[i].value.split("=");
function getUrlParameters(parameter, staticURL, decode) {
var currLocation = (staticURL.length) ? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for (var i = 0; i < parArr.length; i++) {
parr = parArr[i].split("=");
if (parr[0] == parameter) {
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
} else {
returnBool = false;
}
};
if (!returnBool) return false;
};
document.getElementById('Result').value = getUrlParameters("pid", "default.html?pid=405", true);
alert(getUrlParameters("pid", "default.html?pid=405", true));
PID : <input type="text" id="Result" placeholder="Result">
answered Apr 29, 2016 at 20:19
Shady Alset
5,7044 gold badges24 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Lanshore
I tried this, but should I have to code this
alert(getUrlParameters("pid", "default.html?pid=405", true)); is there any way not to have to write it?Shady Alset
@Lanshore no it's just for testing functionality, but where do you want displaying result ?
Lanshore
Post this as answer, I cannot answer myself, I solved it by my own.
Lanshore
function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { vars[key] = value; }); return vars; } var first = getUrlVars()["pid"];Lanshore
This is a better way to get what I needed.
default
parArris actually an array then you would just useparArr[i].split("=")