Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if url param exist using jquery

Tags:

jquery

i saw some similar post at Stack, but i want to ask for specific function in jquery that is

$.urlParam('GETparameter')

Why simple if($.urlParam('GETparameter') === undefined) not working? And why there are complex answers at other questions?

Thank you for answers

like image 528
Raold Avatar asked Aug 17 '16 21:08

Raold


3 Answers

Update 2021

This is an overdue update, but as Frits's solution notes, using URLSearchParams is now the best approach.

const getQueryParameter = (param) => new URLSearchParams(document.location.search.substring(1)).get(param);

Answer from 2016

First off, $.urlParam is not an inherent jQuery function as far as I can tell, meaning you'll need to define it if you plan on using it.

When looking it up, I found a user-created function of the same name; I am going to assume that this is what you're referring to:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

It looks like this will return 0 if the parameter is not found, rather than undefined. If this function is in fact the one you're referencing, you'll want to do this instead:

if($.urlParam('GETparameter') === 0)

like image 93
Tyler Roper Avatar answered Nov 13 '22 14:11

Tyler Roper


Another solution here is the URLSearchParams function.

As an example, if your URL was https://example.com?foo=bar&baz=qux you could retrieve all of the parameters and then query the specific one like this:

var urlParams = new URLSearchParams(window.location.search); //get all parameters
var foo = urlParams.get('foo'); //extract the foo parameter - this will return NULL if foo isn't a parameter

if(foo) { //check if foo parameter is set to anything
    alert('FOO EXISTS');
}

if(foo == 'bar') { //check if foo parameter is 'bar'
    alert('FOO == BAR');
}
like image 11
Frits Avatar answered Nov 13 '22 13:11

Frits


If you want to check type of variable, you need to use something like:

if (typeof($.urlParam('GETparameter')) === 'undefined') {
  ..
}

typeof documentation

like image 1
jacqbus Avatar answered Nov 13 '22 13:11

jacqbus