Appending current URL parameters onto anchor link - javascript

At a page like
https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555
I have a button (anchor link) #ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell that links to https://www.example.com/form
I'd like to append the URL parameters from the current URL to the button's URL, so that the button's href is now https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555
How can I do this with JavaScript please?

Use window.location.search:
var url = "https://exmaple.com";
var newurl = url + window.location.search;
newurl will contain all the get (ex. ?something=something&something2=something5) data.
To change the href of a:
var button = document.getElementById('#ptsBlock_553944');
button.href = button.href + window.location.search;

If you don't care about supporting older browsers you can use the URL API and URLSearchParams.
function appendCurrentUrlSearchParams(anchorElement) {
const currUrlSearchParams = new URL(window.location.href).searchParams;
const link = new URL(anchorElement.href);
// uncomment this line if you want to clear query parameters already present in the anchor url
// link.search = '';
for (const entry of currUrlSearchParams.entries()) {
link.searchParams.append(entry[ 0 ], entry[ 1 ]);
}
anchorElement.href = link.href;
}
Usage in your case:
appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));

Read Html select using select to change the link of a button with Javascript
specifically the section on
Get the element with something like document.getElement MDN getElement Link
Change the .href of that element to what you want.
function selectFunction() {
var x = document.getElementById("selectopt").value;
document.getElementById("mylink").innerHTML = x;
document.getElementById("mylink").href = "http://www." + x + ".com";
}
document.location.pathname = '/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510';
//get the document pathname I chose from document.location
let data = document.location.pathname;
let preUrlString = 'www.example.com/form';
let newString = preUrlString + data;
console.log(newString);
'www.example.com/form/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510'
document.getElementById("mylink").href = newString;

Related

Dynamically generated href won't show properly

So I'm trying to make this link appear on my page, but it won't return the /register path, it'll just go immediately the UTMs.... On the site it'll show the href as
domain.com/?utm_campaign...
instead of
domain.com/register?utm_campaign...
Why is that and how can that be fixed?
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
// get the required parameter
const campaign = urlParams.get('utm_campaign');
const source = urlParams.get('utm_source');
const medium = urlParams.get('utm_medium');
var registerationURL = new URL('../register?utm_campaign=&utm_source=&utm_medium=');
registerationURL.searchParams.set('utm_campaign', campaign);
registerationURL.searchParams.set('utm_source', source);
registerationURL.searchParams.set('utm_medium', medium);
var a = document.getElementbyID('test').innerHTML;
a.href = registerationURL;
</script>
<a id="test" href="#">Click here</a>
document.getElementbyID('test').innerHTML returns the string "Click here". Remove the .innerHTML and it should work.
However, this can be done much simpler with the following
var registrationUrl = location.origin + '/register' + location.search;

How to remove last url location hash using javascript

Am using bootstrap modal on my site, everything a modal is open it will add url has using the modal element id and a data i passed.
My problem is how do i remove the last added hash when a button is clicked just like when browser back button is click window will navigate back removing last hash.
How do i remove last url location has accordingly using javascript, i want every time a button is clicked the last hash from the list of url hash will be removed.
function ensureHash(newHash){
var lochash = location.hash;
if(lochash || lochash != ""){newHash = lochash + "&" + newHash;}
if (window.location.hash) {
return window.location.href.substring(0, window.location.href.lastIndexOf(window.location.hash)) + newHash;
}
return window.location.hash + newHash;
}
window.location.href = ensureHash("modalElementId=modalAction");
https://example.com/app?#mElem1=mAcct1&#mElem2=mAcct2&#mElem4=mAcct5
I tried doing this but it doesn't work well
function ensureRemoveHash(){
var gethash = location.hash;
gethash = gethash.slice(0, gethash.lastIndexOf('&'));
return gethash;
}
window.location.href = ensureRemoveHash();
Something like this?
var str = "https://example.com/app?#mElem1=mAcct1&#mElem2=mAcct2&#mElem4=mAcct5"
function dropHash(str) {
if (str.indexOf("#") ==-1) return str;
var arr = str.split("#");
arr.pop();
return arr.join("#");
}
console.log(str);
str = dropHash(str)
console.log(str);
str = dropHash(str)
console.log(str);
str = dropHash(str)
console.log(str);
Or do you just have the button replace the hash?
var url = new URL("https://example.com/app")
console.log(url);
url.hash="mElem2=mAcct2"
console.log(url);
url.hash="mElem3=mAcct3"
console.log(url);

url formatting using jquery and codeigniter

I have xxx.com and six input fields in a page. If user enter values in the input field I want the URL to be like xxx.com/1st value-2nd value-3rd value-etc
Now I am getting the input values in jQuery and passing those values to the URL but I could pass a single value and not all. Here's my code.
$(".search").on("click",function(e){
// var action = $(this).attr("id");
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "-" + location;
location.href = action;
e.preventDefault();
});
use '/' instead of '-' and get the url parameters in php function like
function($skill='',$location=''){
}
and now script will be like
$(".search").on("click",function(e){
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "/" + location;
location.href = action;
e.preventDefault();
})
Try this one
$(".search").on("click",function(e){
// var action = $(this).attr("id");
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "/" + location;
window.location.href = action;
e.preventDefault();
});
EDIT
Now I have created plunker for you please edit or suggest what you not getting in it, you also edit that plunker and give me new link to it
here is DEMO

javascript window.location update a get data

I have a small javascript issue; I want to reload page with a selected language option value as a get variable.
if I select EN language, the page reload with &lang=EN,
My problem is that I use concat so I get my_url&lang=EN&lang=FR&lang=SP ...
so when I select first EN then FR I want to get my_url&lang=FR not my_url&lang=EN&lang=FR
I want to replace the lang variable not only to add:
<select onchange="javascript:handleSelect(this)">
<option>DE</option>
<option>EN</option>
<option>FR</option>
<option>SP</option>
<option>NL</option>
<option>HR</option>
<option>PL</option>
<option>CZ</option>
</select>
<script type="text/javascript">
function handleSelect(elm)
{
window.location = window.location.href +"?lang="+elm.value;
}
</script>
Try this:
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
{
href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
}
else
{
var char = (href.indexOf("?") == -1 ? "?" : "&");
href+= char + "lang=" + elm.value;
}
window.location.href = href;
}
It should work with any kind of url keeping the params.
Fiddle. In the fiddle I'm using a div instead of the window.location.
try
window.location = window.location.pathname +"?lang="+elm.value;
You could use the replace function:
window.location = window.location.href.match(/lang=/) ? window.location.replace( /lang=(.*){2}/, 'lang=' + elm.value ) : window.location.href + '?lang=' + elm.value;
Reference: http://www.w3schools.com/jsref/jsref_replace.asp
If ?lang= exists, replace it with the new one.
If not, just add the lang parameter.
edit
I like the window.location.pathname solution from Dave Pile, this should be better than checking and replacing something.
edit2
var loc = 'http://test.de/?foo=bar'; // window.location.href;
var seperator = loc.match(/\?/) ? '&' : '?';
var elm = 'DE';
var url = loc.match(/lang/) ? loc.replace(/lang=(.*){2}/, 'lang' + elm ) : loc + seperator + 'lang=' + elm;
document.getElementById('result').innerHTML = url;
<div id="result"></div>
Look at this snippet, you have to change the loc so it should work, also change var url to window.location and elm to your language element.
It checks if parameters exists and change the seperator from ? to &, than if no lang is set, it will set it or if a lang is set, it will replace it.
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
window.location.href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
else
window.location = window.location.href +"&lang="+elm.value;
}
You could use
var currAddress = window.location.href;
var indexOfLang = currAddress.indexOf('lang=');
var tempAddress = currAddress.substring(indexOfLang, indexOfLang+7);
currAddress = currAddress.replace(tempAddress,'lang='+elm.value);
window.location = currAddress;
The number 7 is the length of substring - lang=EN.

Converting URL into clickable link using Javascript

I have a text field called 'patentURL' in a form. The user enteres the complete URL into this field while saving the record. When the user searches for this record, the entered URL should be clickable. i.e. in the result page, the entered URL should be clickable.
How do I achieve this using Javascript?
There is a non-standard function, but widely spread - link() MDC
function makeClickable(url) {
return String.prototype.link ? url.link(url) : ''+url+'';
}
function makeDOMClickable(url) {
var link = document.createElement('a');
link.href = url;
link.innerHTML = url;
return link;
}
var url = "http://localhost";
document.write ( makeClickable ( url ) );
document.body.appendChild ( makeDOMClickable ( url ) );
demo
If i understood correctly you should put the url in a link:
URL_ENTERED
With javascript:
var link = document.createElement('a');//create link
link.setAttribute('href', 'URL_ENTERED');//set href
link.innerHTML = 'URL_ENTERED';//set text to be seen
document.body.appendChild(link);//add to body
You can use javascript regular expression to achieve this have a look
function convert()
{
var text=document.getElementById("url").value;
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var text1=text.replace(exp, "<a href='$1'>$1</a>");
var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
document.getElementById("converted_url").innerHTML=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
}
this way you can convert any text into link you can find more detail here http://talkerscode.com/webtricks/convert-url-text-into-clickable-html-links-using-javascript.php
Example to call href in Javascript:
function call_link() {
location.href = 'www.google.com';
}

Categories