En una página como
https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555
Tengo un botón (enlace de anclaje) #ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell que enlaza con https://www.example.com/form
Me gustaría agregar los parámetros de URL de la URL actual a la URL del botón, de modo que el href del botón ahora sea https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555
¿Cómo puedo hacer esto con JavaScript, por favor?
Utilice window.location.search :
var url = "https://exmaple.com"; var newurl = url + window.location.search; newurl contendrá todos los datos get (por ejemplo, ?something=something&something2=something5 ).
Para cambiar el href de a :
var button = document.getElementById('#ptsBlock_553944'); button.href = button.href + window.location.search;Si no le importa admitir navegadores más antiguos, puede usar la API de URL y 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; }Uso en su caso:
appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));Lea Html select usando select para cambiar el enlace de un botón con Javascript
específicamente la sección de
Obtenga el elemento con algo como document.getElement MDN getElement Link
Cambia el .href de ese elemento a lo que quieras.
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;