1

I am trying to check if a search has been ran so that i can react to this with JS and hide and show different divs depending on that on page load.

How do i get information from the URL with JavaScript and Jquery?

www.localhost.com/search?name=&category=

I want to get the information of the name and category then if they are not null i want to show this div

<div class="Search-results"></div>

and hide this one

<div class="Search-params"></div>

Is this even possible?

detinu20
  • 299
  • 3
  • 20
  • 1
    Possible duplicate of [Get url parameter jquery Or How to Get Query String Values In js](https://stackoverflow.com/questions/19491336/get-url-parameter-jquery-or-how-to-get-query-string-values-in-js) – Stelios Joseph Karras May 27 '18 at 22:41
  • Read this https://stackoverflow.com/questions/814613/how-to-read-get-data-from-a-url-using-javascript – Emeeus May 27 '18 at 22:42

2 Answers2

1

Many of the solutions on this site were done before the newer URL API was implemented and involve parsing strings

Use URL.searchParams which has numerous methods for getting, setting and iterating keys and values without having to parse strings

const url =new URL('http://www.localhost.com/search?foo=bar&name=&category=')
const params = url.searchParams;

// check if 2 params exist and have values
if(!params.get('name') && !params.get('category')){
  console.log('name & category are empty or not available')
}
// output value of valid param
console.log('value of foo = ', params.get('foo'))

// add a new param and output updated href string
params.set('new-param', 123);
console.log('Updated url\n', url.href)

// loop through all params
for(let p of params){
   console.log('value of', p[0] , ' is ', p[1] || 'empty')
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • nice man i can see what your doing but i cannot get it to work on my code. Says the searchParams is undefined and just runs the if no matter whether the params are null or not. Any ideas>? – detinu20 May 28 '18 at 00:32
  • Are you using full url with protocol? If Is parsing from current page can use `url = URL(location.href)`. Would need to see your code to help – charlietfl May 28 '18 at 00:38
0

This works :

if(!searchParams.get('name') && !searchParams.get('category')){

  }
  else{

        $('.search').hide()


}
detinu20
  • 299
  • 3
  • 20