I'm using a PHP framework Codeigniter that uses segment based urls like http://www.mydomain.com/age/11/name/john/color/red
instead of the usual querystrings lijke http://www.mydomain.com/index.php?age=11&name=john&color=red
.
How do I grab the value of the age
key from the url using Javascript/jQuery?
After grabbing the value 11
I will pass it into a jQuery object when an event is fired.
$( "#searchdistance_slider" ).slider({
range: "min",
value: 5,
min: 0.5,
max: 10,
slide: function( event, ui ) {
$( "#search_distance" ).val(ui.value + " miles");
window.location.replace("http://www.domain.com/" + age);
/* passing the value of age into URL to redirect to */
}
});
UPDATE
age
, and the new value 20
from the slider will be use to redirect the user to http://www.mydomain.com/age/20/name/john/color/red
You could try using the jQuery URL parser plugin.
Use the .segment(n)
call to search the URL path for "age"
, and grab the next one which should contain the age value you're looking for.
Or try the .fsegment(n)
method if age
is always in the same position.
Or use .segment()
with something like:
var parts = $.url(your_url).segment();
var params = [];
for (var i=0; i<parts.length/2; i++) {
params[parts[2*i]] = parts[2*i+1];
}
var age = parseInt(params['age']);
(I'm sure there's a prettier way to do that though.)
If you only want the age
part, you don't have to do all that stuffing into a dictionary. Just exit the loop early when you've found the key you want.
If you want to reconstruct the path with a changed age, try something like:
var parts = $.url(your_url).segment();
var newpath = '';
for (var i=0; i<parts.length/2; i++) {
if (parts[2*i] == 'age') {
newpath += '/age/' + (parseInt(parts[2*i+1]) + 42); // put your age modifiy
// code here
} else {
newpath += '/' + parts[2*i] + '/' + parts[2*i+1];
}
}
alert(newpath);
You could split it with something like this:
var parts = {},
bits = location.pathname.substr(1).split('/'); // get rid of first / and split on slashes
for (var i = 0; i<bits.length; i += 2) {
parts[bits[i]] = bits[i+1];
}
You could then access the age
value with parts.age
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With