Skip to content Skip to sidebar Skip to footer

Function To Retrieve Url Variables Using Javascript And Jquery?

Solution 2:

You could try this:

JavScript

functiongetUrlParams() {
    var params = {};
    location.search.replace(/\?/g, '').split('&').forEach(function(item) {
      params[item.split('=')[0]] = item.split('=')[1];
    });
    return params;
}

The function will return an object like this:

{
  firstName: 'Jordan',
  lastName: 'Belfort',
  position: 'The Wolf of Wall Street',
}

Usage

var urlParams = getUrlParams();
alert('Hello ' + urlParams.firstName + ' ' + urlParams.lastName);

Note: There's actually no need to use location.href and split the url at '?', since we can get the whole query string with location.search.

Solution 3:

As an alternative to your problem, why not put the id part of the href into a data parameter and read that? It would save you having to dissect the URL. Try this:

<ul><li><ahref="edit.php?id=5"data-id="5"class="edit">click here</a></li><li><ahref="edit.php?id=6"data-id="6"class="edit">click here</a></li><li><ahref="edit.php?id=7"data-id="7"class="edit">click here</a></li><li><ahref="edit.php?id=8"data-id="8"class="edit">click here</a></li></ul>
$('.edit').click(function(){
    var id = $(this).data("id");
    alert(id);
});

Solution 4:

Try this one:

functiongetParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = newRegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return"";
  elsereturndecodeURIComponent(results[1].replace(/\+/g, " "));
}

Solution 5:

You almost got it right the first time, you just have to declare vars as object and get rid of vars.push(...).

Here's working example - http://jsfiddle.net/KN9aK/1/show/?id=yoursuperduperid

Source here http://jsfiddle.net/KN9aK/1/

Post a Comment for "Function To Retrieve Url Variables Using Javascript And Jquery?"