I have an anchor like <a href="/category/post/?type=234#content">link</a>. Using a jQuery is it possible to get the value of "type" in URL and assign as a value for a hidden input type in same page without refreshing the page.
Asked
Active
Viewed 669 times
0
-
See http://stackoverflow.com/questions/872217/jquery-how-to-extract-value-from-href-tag – Castrohenge Sep 15 '10 at 14:57
-
1I think this is a duplicate of http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery and http://stackoverflow.com/questions/901115/get-querystring-with-jquery/901144#901144 – davehauser Sep 15 '10 at 14:58
2 Answers
1
$(function() {
var val = $('a').attr('href').match(/type\=\d+/)[0].replace(/type\=/,'');
$('input[type=hidden]').val(val);
});
example :
var href = "/category/post/?type=234#content";
var filter = href.match(/type\=\d+/)[0].replace(/type\=/,'')
console.log(filter);
-
but i only need the value of type and use it as value for hidden input type – daron Sep 15 '10 at 14:59
-
0
I'd written a function to get the querystring parameters as a map a while ago:
/**
* Gets the query parameters of the given URI as a associative array or map
* e.g. Given a URI http://www.level3labs.com/jaf?foo=bar&baz=bazzm, will
* give {"foo":"bar", "baz":"bazzm"}
* @param {URI} strUri The uri with a query
* @return Object containing query params or and empty object
*/
function getQueryParams(strUri) {
var paramMap = {};
if(!strUri) {
return paramMap;
}
var strQuery = strUri.substring(strUri.indexOf("?"));
if(strQuery.lastIndexOf("#") !== -1) {
strQuery = strQuery.substring(0, strQuery.lastIndexOf("#"));
}
if(strQuery && strQuery.indexOf("?") === 0 && strQuery.length > 1) {
strQuery = strQuery.substring(1);
var paramValArr = strQuery.split("&");
for(var i = 0, len = paramValArr.length; i < len; i++) {
var paramVal = paramValArr[i];
var delimIdx = paramVal.indexOf("=");
var param = null;
var val = null;
if(delimIdx >= 0) {
param = unescape(paramVal.substring(0, delimIdx));
val = unescape(paramVal.substring(delimIdx + 1));
}else {
param = unescape(paramVal);
}
paramMap[param] = val;
}
}
return paramMap;
}
This can be used in conjunction with the code below:
var uri = $('a').attr('href');
var params = getQueryParams(uri);
$('input[type=hidden]').val(params["type"]));

naikus
- 24,302
- 4
- 42
- 43
-
-
@daron Updated my answer (function code) to handle fragments. Now you will get proper name-value pairs – naikus Sep 16 '10 at 04:34