Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change url query string value using jQuery [duplicate]

I have an example URL like:

http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01

The query string contains the current page number and two additional filters (name and date).

Using the following URL parser: https://github.com/allmarkedup/purl I am able to access certain parts of the URL such as just the page number.

I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.

$(document).ready(function () {          $('.pageNum').live('keyup', function (e) {             e.preventDefault();             if (e.which == 13) {                  var currentUrl = window.location.href;                  var parsedUrl = $.url(currentUrl);                  var currentPageNum = parsedUrl.param('page');                  var newPageNum = $(this).val();                  var newUrl = //                  window.location.href = newUrl;              }         });      }); 

So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.

Is it possible to change the param value and then add it back in?

Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!

like image 488
Cameron Avatar asked Jun 20 '13 10:06

Cameron


People also ask

How can I add or update a query string parameter?

set('PARAM_HERE', VALUE_HERE); history. pushState(null, '', url); This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.

How do I change the value of URL?

If you have several parameters with the same name, you can append to the regex global flag, like this text. replace(/(src=). *?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.

How do you change a query string?

Edit / Update a ParameterAfter setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object. The final new url can then be retrieved with the toString() method of the URL object.


1 Answers

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum); 
like image 60
Kaizo Avatar answered Oct 09 '22 22:10

Kaizo