Reputation: 2614
A link of mine may look like:
<a href="/some/where?id=123">click</a>
When the link is clicked, my handler is triggered:
$(document).on("click", "a", function (e) {
e.preventDefault();
var hrefAttribute = $(this).attr("href"); // "/some/where?id=123"
console.log(hrefAttribute);
});
hrefAttribute contains "/some/where?id=123".
What I would like, is to extract the value of the parameter called id. Hence the value "123"
As more attributes may be added to the url over time, I prefer not to extract the parameter value by string manipulation. A JQuery select value by parameter name would be better if possible.
Upvotes: 0
Views: 253
Reputation: 24638
You can use a regular expression to extract the id
as follows:
var hrefAttribute = $(this).attr("href"),
id = hrefAttribute.replace(/^*id=(\d+)\b.*$/g,'$1');
console.log( id );
$(document).on("click", "a", function (e) {
e.preventDefault();
var hrefAttribute = $(this).attr("href"),
id = hrefAttribute.replace(/^.*id=(\d+)\b.*$/g,'$1');
console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/some/where?jsd=5567&id=123">click</a>
When the link is clicked, my handler is triggered:
Another approach would be to use the .forEach()
array method:
function getQParam(url, param) {
var oParam = {};
url.indexOf('?') === 0 || url.split('?')[1].split('&').forEach(function(v) {
oParam[ v.split('=')[0] ] = v.split('=')[1];
});
return oParam[ param ];
}
var id = getQParam( this.href, 'id' );
function getQParam(url, param) {
var oParam = {};
url.indexOf('?') === 0 || url.split('?')[1].split('&').forEach(function(v) {
oParam[ v.split('=')[0] ] = v.split('=')[1];
});
return oParam[ param ];
}
$(document).on("click", "a", function (e) {
e.preventDefault();
var id = getQParam( this.href, 'id' );
console.log( id );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/some/where?id=123">click</a>
When the link is clicked, my handler is triggered:
Upvotes: 1
Reputation: 707158
There is no way to obtain the 123
without some string manipulation of the href
attribute. You can, however, design that string manipulation so that it will still work even if other query arguments are added to the href
.
For example, you could use a general purpose function for extracting a query parameter from a URL like this:
// returns the query argument for the given key or undefined if the key is not found
function getParam(url, key) {
var regex = new RegExp("\\?.*?" + key + "=" + "(.*?)(&|$)");
var matches = url.match(regex);
if (matches) {
return matches[1];
}
}
var id = getParam(this.href, "id");
Working demo: http://jsfiddle.net/jfriend00/3uxwe2ce/
Upvotes: 1
Reputation: 62
According to jQuery API documentation:
$(this).attr("href", "/some/where?id=123");
If you want to put a dynamic URL you have to use $.ajax()
Upvotes: 0