how to prevent new element being appended repeatedly in javascript function? - javascript

Currently I have a JavaScript function like this:
<script type="text/javascript">
function select_device(device)
{
var mylink = window.location.href + "&name=" + device.value;
window.location.replace(mylink);
window.history.back
}
</script>
When a variable pass in, it will add as a new element into the url. Is there any way that I could possibly pass the variable in smartly as it will not just append repeatedly to the existing address?
I have tried to do it like
const url = window.location
window.location.replace(url.hostname + url.pathname + url.search + "&name=" + device.value)
But it doesn't solve the problem.

Since it sounds like you have multiple search parameters, not just name (since you're using &, not ? at the beginning), use URLSearchParams from the search string, set the new name, and then turn it back into a string:
function select_device(device) {
const { pathname, search } = window.location;
const params = new URLSearchParams(search);
params.set('name', device);
window.location.replace(pathname + '?' + String(params))
}

Related

Add a variable in URL instead of replacing one

I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;

remove parameter from url via regex

I have a function for removing the parameter from url.
this is my function :
function removeParameter(key) {
let parameters = document.location.search;
const regParameter = new RegExp('[?|&]' + key + "=([a-zA-Z0-9_-]+)");
if (regParameter.test(parameters)){
parameters = parameters.replace(regParameter , '')
}
window.history.pushState({}, '', parameters)}
when I call this function for the url like this
http://example.com/products?color=4&brand=apple
first call function for removing the brand is correct result
removeParameter('brand')
but another call this function for removing the color doesn't work correctly.
actually when i want to removing the first parameter(key come's after ? mark) this function doesn't work...
The third argument to pushState() is the entire URL. Your function is sending only the location.search i.e. query parameter part of the URL. So you'll need to do
window.history.pushState({}, '', location.pathname + parameters)}
on your function's last line. Also, your code is currently not handling the edge cases i.e. if you remove first parameter, it removes the ? and not the trailing &. So you end up with http://example.com/products&brand=apple which isn't a valid URL. And finally, I simplified your expression a bit.
const reg = new RegExp('[?&](' + key + '=[\\w-]+&?)');
let matches = reg.exec(parameters);
if (matches){
parameters = parameters.replace(matches[1], '');
}
This still doesn't handle more complex cases (params without values, hash etc). There are a couple of other options:
Dump the regex and go with a split('&') based solution. More code, but a lot more readable and less error-prone.
If you don't need IE support, use URLSearchParams. Then your entire function can be reduced to this:
var params = new URLSearchParams(location.search);
params.delete(key);
window.history.pushState({}, '', location.pathname + "?" + params.toString());
Correct me if I'm wrong,
I made a working snippet out of your code, and it seems to work correctly.
If you run the snippet on a fresh new tab, it will add 2 urls in the tab history.
I also modified your regex to make it easier.
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp('[?|&]' + key + "=([^&]+)"); // TAKIT: Simplified regex
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
}
window.history.pushState({}, 'Test 1', parameters);
return parameters; // TAKIT: Added
}
// Output
var url = "https://stacksnippets.net/js?color=4&brand=apple";
console.log(url);
url = removeParameter("brand");
console.log(url);
url = removeParameter("color");
console.log(url);
Hope it helps.
This function can be used, i modified #Takit Isy answer
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp(key + "=([a-zA-Z0-9_-]+[&]{0,1})");
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
if(parameters.substring(parameters.length-1)=='?' || parameters.substring(parameters.length-1)=='&'){
parameters = parameters.slice(0, -1);
}
}
return parameters; // TAKIT: Added
}

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

Change url query string value using jQuery [duplicate]

This question already has answers here:
Updating existing URL querystring values with jQuery
(12 answers)
Closed 9 years ago.
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!
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
purls $.params() used without a parameter will give you a key-value object of the parameters.
jQuerys $.param() will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);

Is this JavaScript encoding properly written?

I have tried some tips I was given on regards URL encoding but I have no success so far. First, I was given this format,
var url = "http://www.polyvore.com/cgi/add?title="
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&url=" + encodeURIComponent("http://lilaboutique.co.uk/products/"
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&imgurl=" + encodeURIComponent(%%GLOBAL_ThumbImageURL%%)
+ "&desc=" + encodeURIComponent(%%GLOBAL_ProductDesc%%)
+ "&price=" + encodeURIComponent(%%GLOBAL_ProductPrice%%));
which never got to be passed to the href dunno for what reason. Then I played with it some more,
var url = "http://www.polyvore.com/cgi/add?title=encodeURIComponent(%%GLOBAL_ProductName%%)&url=http://lilaboutique.co.uk/products/encodeURIComponent(%%GLOBAL_ProductName%%)&imgurl=encodeURIComponent(%%GLOBAL_ThumbImageURL%%)&desc=encodeURIComponent(%%GLOBAL_ProductDesc%%)&price=encodeURIComponent(%%GLOBAL_ProductPrice%%)";
this time the URL was passed but the values were mixed between the appropriate and other fields displaying the encoding function itself.
Any help clarifying my mistakes is greatly appreciated. I would like to encode just price and description, seems to be the fields giving problems.
A regular link does render without problems
var url = "www.google.com";
var myAnchor = document.getElementById('myAnchor');
myAnchor.href = url;
Thanks for any help
Nicer, cleaner way of doing this:
var toEncode = {
title: '%%GLOBAL_ProductName%%',
url: 'http://lilaboutique.co.uk/products/%%GLOBAL_ProductName%%',
imgurl: '%%GLOBAL_ThumbImageURL%%',
desc: '%%GLOBAL_ProductDesc%%',
price: '%%GLOBAL_ProductPrice%%'
};
var index, queryString = '';
for (index in toEncode)
{
queryString += index + '=' + encodeURIComponent(toEncode[index]) + '&';
}
var url = "http://www.polyvore.com/cgi/add?" + queryString;
jQuery's $.param(obj) is very nice.
In general though I would take a similar approach if you wanted to roll your own. Make a function that accepts an Object, and returns a query string. Then in your server template, you have:
var urlData = {
url: "http://lilaboutique.co.uk/products/",
imgurl: "%%GLOBAL_ThumbImageURL%%",
desc: "%%GLOBAL_ProductDesc%%"
// etc...
}
var url = "http://www.polyvore.com/cgi/add?" + $.param(urlData);
Or whatever conversion function you want to use.

Categories