Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  200] [ 4]  / answers: 1 / hits: 19365  / 11 Years ago, sun, april 7, 2013, 12:00:00

I have a form that uses the get method and contains an array:



http://www.example.com?name[]=hello&name[]=world



I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.



I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.



Is it possible to get array values?


More From » arrays

 Answers
11

There you go: http://jsfiddle.net/mm6Bt/1/



function getURLParam(key,target){
var values = [];
if (!target) target = location.href;

key = key.replace(/[[]/, \[).replace(/[]]/, \]);

var pattern = key + '=([^&#]+)';
var o_reg = new RegExp(pattern,'ig');
while (true){
var matches = o_reg.exec(target);
if (matches && matches[1]){
values.push(matches[1]);
} else {
break;
}
}

if (!values.length){
return null;
} else {
return values.length == 1 ? values[0] : values;
}
}

var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';

console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));

[#79068] Friday, April 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;