jQuery: simplest way to check URL for a parameter and pass it to anchor href if it exists
Client side the simplest is use the URL API
var mainUrl = new URL(location.href);// Won't work in this demo so hard code hrefmainUrl = new URL('http://example.com?a=foo&b=2');
var paramA = mainUrl.searchParams.get('a');
$('a.hyperlink').prop('href', function(){ var url = new URL(this.href); url.searchParams.set('a', paramA); return url;})// set query params as text just for demo.text(function(){ return 'Query Params: ' + this.search;})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="page1.php?a=1" class="hyperlink">Link 1</a><br/><a href="page2.php?b=1&a=1" class="hyperlink">Link 2</a>
How to get URL parameter using jQuery or plain JavaScript?
Best solution here.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
And this is how you can use this function assuming the URL is,http://dummy.com/?technology=jquery&blog=jquerybyexample
.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
How to get the parameters of an href attribute of a link from the click event object
You can use the this.href
method to read the link attribute:
$('#pages').delegate("a", "click", function(e) {
var str = this.href.split('?')[1];
Example:
str = 'friends.php?term=ma&p=2';
console.log(str.split('?')[1]); // output: term=ma&p=2
Check whether a URL variable is set using JQuery
jQuery doesn't have native functions to get URL parameters.
But you can write your own plugin to it:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
Then you can do anything like it:
if ($.getUrlVar("MyParam") != null) {
// Do anything...
}
Javascript need to pass variable using <a href> link with id
Try this:
$("a.selector").live("click", function() {
var url = $(this).attr('href');
$(".overlayInner").load(url);
return false;
});
<a class="selector" href="/country.php">Country</a>
<a class="selector" href="/pigs.php">Pigs</a>
If you want to get the inner text that says "Country", or an image you can do:
$("a.selector").live("click", function() {
var url = $(this).attr('href');
var img = $(this).html(); // But what do you want to do with it?
$(".overlayInner").load(url);
return false;
});
<a class="selector" href="/country.php"><img src="img.jpg" /></a>
How can you check for a #hash in a URL using JavaScript?
Simple use of location hash:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
Get query string parameters url values with jQuery / Javascript (querystring)
After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
//Assuming URL has "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?
post=1234&action=edit&active=1"
UPDATE : IE is not supporteduse this function from an answer below instead of URLSearchParams
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('action')); //edit
Passing parameters in link jquery mobile
Several solutions exist:
Solution 1:
You can pass values with changePage:
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
And read them like this:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});
$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->
</body>
</html>
second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">
</div> <!--content-->
</div><!--page-->
</body>
</html>
Solution 2:
Or you can create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.
var storeObject = {
firstname : '',
lastname : ''
}
Example: http://jsfiddle.net/Gajotres/9KKbx/
Solution 3:
You can also access data from the previous page like this:
$(document).on('pagebeforeshow', '#index',function (e, data) {
alert(data.prevPage.attr('id'));
});
prevPage object holds a complete previous page.
Solution 4:
As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
Example: http://jsfiddle.net/Gajotres/J9NTr/
Find more about them here.
How to change the href attribute for a hyperlink using jQuery
Using
$("a").attr("href", "http://www.google.com/")
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
...Then you probably don't want to accidentally add href
attributes to them. For safety then, we can specify that our selector will only match <a>
tags with an existing href
attribute:
$("a[href]") //...
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href
, you might use something like this:
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
This will find links where the href
exactly matches the string http://www.google.com/
. A more involved task might be matching, then updating only part of the href
:
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
The first part selects only links where the href starts with http://stackoverflow.com
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
How to get href value using jQuery?
You need
var href = $(this).attr('href');
Inside a jQuery click handler, the this
object refers to the element clicked, whereas in your case you're always getting the href for the first <a>
on the page. This, incidentally, is why your example works but your real code doesn't
Related Topics
Javascript Function Not Defined Error (But It Is Defined)
Convert Date/Time in Gmt to Est in JavaScript
Remove Insignificant Trailing Zeros from a Number
How to Change Color of Ag-Grid Cells for Dynamically Changing Data
How to Replace Double/Multiple Slash to Single in Url
Get a Value from a Observable<Value> Object
How to Get Public User All Posts from Instagram, Without Instagram API
Safari: Focus Event Doesn't Work on Button Element
How to Get First N Number of Elements from an Array
Regex to Replace Everything Except Numbers and a Decimal Point
Dynamically Add Variable Name Value Pairs to Json Object
How to Append Value to an Array Only If Not Exists and Remove It If Not
How to Check If a Textbox Is Empty Using JavaScript
Stretch Height to Fit Content in React Native
How to Clear Input After Onclick With Reactjs
Select Li Element With Arrow Keys (Up and Down) Using JavaScript (Jquery)